移动相应的py文件时自动删除pyc文件(Mercurial)

15 投票
7 回答
8038 浏览
提问于 2025-04-15 20:55

(我三个月前就预见到这个问题可能会发生,并被告知要小心以避免它。昨天,我真的遇到了这个问题,而且损失了不少钱,现在我迫切想要解决它。)

如果我把一个Python源文件移动到另一个文件夹,我需要记得告诉Mercurial它已经移动了(hg move)。

当我用Mercurial把新软件部署到我的服务器时,它会小心翼翼地删除旧的Python文件,并在新文件夹里创建一个新的。

不过,Mercurial并不知道同一文件夹里的pyc文件,结果就把它留了下来。其他模块会优先使用旧的pyc文件,而不是新的Python文件。

接下来发生的事情可不是好笑的。

我该如何让Mercurial在我移动Python文件时自动删除旧的pyc文件呢?有没有更好的做法?试着记得从所有Mercurial仓库中删除pyc文件并不奏效。

7 个回答

9

你可以在服务器上使用一个叫做更新钩子的东西吗?把下面的内容放到你仓库的.hg目录下的hgrc文件里:

[hooks]
update = find . -name '*.pyc' | xargs rm

这样一来,每当你在服务器上更新时,所有的.pyc文件就会被删除。如果你担心重新生成所有.pyc文件的时间太长,你可以在钩子里做得更聪明一点,只删除那些没有对应.py文件的.pyc文件,不过这样可能就有点过于复杂了。

16

1. 不要把 .pyc 文件放在代码库里。

2. 可以用这个命令自动删除 .pyc 文件:find . -name '*.pyc' -delete

3. 在开发的时候,使用 Python 的 -B 参数。

3

我做了以下几件事:

1) 我在考虑Nicholas Knight的建议,想用一个合适的部署策略。我一直在阅读关于BuildoutCollective.hostout的资料,想了解更多。我需要决定这些比较复杂的策略是否适合我这个项目相对简单的需求。

2) 在我做决定之前,我暂时采用了Ry4an的更新钩子概念。

3) 我忽略了Ry4an关于过度设计的警告,写了一个Python脚本,只用来删除多余的.pyc文件。

#!/usr/bin/env python
""" Searches subdirectories of the current directory looking for .pyc files which
    do not have matching .py files, and deletes them.

    This is useful as a hook for version control when Python files are moved.
    It is dangerous for projects that deliberately include Python 
    binaries without source.
"""
import os
import os.path
for root, dirs, files in os.walk("."):
    pyc_files = filter(lambda filename: filename.endswith(".pyc"), files)
    py_files = set(filter(lambda filename: filename.endswith(".py"), files))
    excess_pyc_files = filter(lambda pyc_filename: pyc_filename[:-1] not in py_files, pyc_files)
    for excess_pyc_file in excess_pyc_files:
        full_path = os.path.join(root, excess_pyc_file)
        print "Removing old PYC file:", full_path
        os.remove(full_path)

现在我的更新钩子调用这个脚本,而不是其他人建议的“查找”命令。

撰写回答