[英]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 中提交,只需
/__pycache__
,.pyc
不會再次出現。扎卡里的回答是正確的。 在您的情況下它可能是正確的原因是 gitignore 不適用於預先存在 gitignore(或存儲庫)的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.