如何避免.pyc文件?

2024-04-20 01:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
import sys

sys.dont_write_bytecode = True

实际上,在Python2.3+中有一种方法可以做到这一点,但这有点深奥。我不知道你是否意识到这一点,但你可以做以下事情:

$ unzip -l /tmp/example.zip
 Archive:  /tmp/example.zip
   Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32) 
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'

根据zipimport库:

Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn't contain .pyc files, importing may be rather slow.

因此,您只需压缩文件,将zipfile添加到sys.path,然后导入它们。

如果您正在为UNIX构建这个脚本,您也可以考虑使用这个配方打包您的脚本:unix zip executable,但是请注意,如果您计划使用stdin或从sys.args读取任何内容,则可能需要对此进行调整(这样做不会带来太多麻烦)。

根据我的经验,性能不会因此而受到太大的影响,但是在以这种方式导入任何非常大的模块之前,您应该三思而后行。

来自"What’s New in Python 2.6 - Interpreter Changes"

Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.dont_write_bytecode variable, and Python code can change the value to modify the interpreter’s behaviour.

更新2010-11-27:Python 3.2通过引入一个特殊的__pycache__子文件夹来解决用.pyc文件混乱源文件夹的问题,请参见What's New in Python 3.2 - PYC Repository Directories

相关问题 更多 >