如何让 CPython 2.7 使用 __pycache__ 目录?

How do I let CPython 2.7 use the __pycache__ directory?

CPython 3.x 和 PyPy 遵循 PEP 3147 并将 pyc 文件存储在 __pycache__ 目录中,并附加了 Python 版本后缀。 我如何强制 CPython 2.7 将其 pyc 文件也存储在 __pycache__ 目录 中(与其存储没有后缀的 pyc 文件的默认行为相反)在同一目录中相应的 py 文件旁边)?

我意识到我可能不应该在系统范围内执行此操作,因为很多其他软件都期望 CPython 2.x 的默认行为。所以我正在寻找一种方法来针对每个项目或每个虚拟环境执行此操作,或者,如果没有其他解决方案,则根据自定义编译和自定义安装(例如在 ~/bin 中)CPython 解释器。


一些研究:Relevant discussion on Debian mailing list; code review 在 CPython 3.2 中实现 PEP 3147。

虽然 PEP 3147 的 backports 部分暗示了它被移植回来的可能性:

For versions of Python earlier than 3.2 (and possibly 2.7), it is possible to backport this PEP. However, in Python 3.2 (and possibly 2.7), this behavior will be turned on by default, and in fact, it will replace the old behavior.

据我所知,这还没有完成。讨论 here 说明了原因:

I would prefer that this not be in 2.7. The patch may be simple to port, but it represents quite a change in an eons old Python behvior.

这是 Python 2.7 的发布经理的回复,他(正确的恕我直言)不希望此功能被移植回来。

最后,您唯一的选择就是自己实施(这是一项非常重要的任务)。