在git仓库中忽略.pyc文件

156 投票
7 回答
203852 浏览
提问于 2025-04-16 15:07

我该怎么在git中忽略.pyc文件呢?

如果我把它放进.gitignore文件里,它好像不起作用。我希望这些文件不被跟踪,也不被检查是否要提交。

7 个回答

97

你可能在把 *.pyc 加入 .gitignore 之前,就已经把它们添加到代码库里了。
首先,你需要把它们从代码库中删除。

334

你应该在你的git仓库根目录下的.gitignore文件中添加一行:

*.pyc 

这应该在你初始化仓库后立即进行。

正如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/)

46

把它放进 .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 文件里(包括根目录)。

撰写回答