繁体   English   中英

忽略 git 存储库中的 .pyc 文件

[英]Ignore .pyc files in git repository

如何忽略 git 中的.pyc文件?

如果我把它放在.gitignore中,它就不起作用。 我需要他们不被跟踪并且不检查提交。

您应该添加一行:

*.pyc 

存储库初始化后立即转到 git 存储库树根文件夹中的.gitignore文件。

正如ralphtheninja所说,如果您事先忘记这样做,如果您只是将这一行添加到.gitignore文件中,那么所有先前提交的.pyc文件仍将被跟踪,因此您需要将它们从存储库中删除。

如果您使用的是 Linux 系统(或 MacOSX 之类的“父母和儿子”),则只需使用需要从存储库根目录执行的这一行命令即可快速完成:

find . -name "*.pyc" -exec git rm -f "{}" \;

这只是意味着:

从我当前所在的目录开始,查找名称以扩展名.pyc结尾的所有文件,并将文件名传递给命令git rm -f

从 git 中删除*.pyc文件作为跟踪文件后,将此更改提交到存储库,然后您最终可以将*.pyc行添加到.gitignore文件中。

(改编自http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/

在将*.pyc放入.gitignore之前,您可能已经将它们添加到存储库中。
首先从存储库中删除它们。

把它放在.gitignore 但是从gitignore(5)手册页:

 · If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file). · Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, "Documentation/*.html" matches "Documentation/git.html" but not "Documentation/ppc/ppc.html" or "tools/perf/Documentation/perf.html".

因此,要么指定适当的*.pyc条目的完整路径,要么将其放在从存储库根目录(包括在内)开始的任何目录中的.gitignore文件中。

如果您想全局忽略“.pyc”文件(即,如果您不想在每个 git 目录的 .gitignore 文件中添加该行),请尝试以下操作:

$ cat ~/.gitconfig 
[core]
    excludesFile = ~/.gitignore
$ cat ~/.gitignore
**/*.pyc

[参考]
https://git-scm.com/docs/gitignore

  • 用户希望 Git 在所有情况下忽略的模式(例如,由用户选择的编辑器生成的备份或临时文件)通常会进入用户的 ~/.gitconfig 中由 core.excludesFile 指定的文件。

  • 前导“**”后跟斜杠表示在所有目录中匹配。 例如,“**/foo”匹配任意位置的文件或目录“foo”,与模式“foo”相同。 "**/foo/bar" 匹配直接位于目录 "foo" 下的任何位置的文件或目录 "bar"。

我尝试使用先前帖子的句子并且不递归工作,然后阅读一些帮助并获得以下行:

find . -name "*.pyc" -exec git rm -f "{}" \;

pd 需要在 .gitignore 文件中添加 *.pyc 以保持 git clean

echo "*.pyc" >> .gitignore

享受。

感谢@Enrico 的回答。

请注意,如果您使用的是 virtualenv,那么您当前所在的目录中将有多个.pyc文件,这些文件将被他的 find 命令捕获。

例如:

./app.pyc
./lib/python2.7/_weakrefset.pyc
./lib/python2.7/abc.pyc
./lib/python2.7/codecs.pyc
./lib/python2.7/copy_reg.pyc
./lib/python2.7/site-packages/alembic/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/api.pyc

我认为删除所有文件是无害的,但是如果您只想删除主目录中的.pyc文件,那么只需执行

find "*.pyc" -exec git rm -f "{}" \\;

这将app.pyc git 存储库中删除app.pyc文件。

如果你已经在 repo 中提交,只需

  1. 转到文件夹/__pycache__
  2. 全部删除(不用担心,它们是临时文件并重复生成)
  3. 有一个新的提交,例如“更新 gitignore”
  4. 你完成了! .pyc不会再次出现。

扎卡里的回答是正确的。 在您的情况下它可能是正确的原因是 gitignore 不适用于预先存在 gitignore(或存储库)的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM