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读取任何内容,则可能需要对此进行调整(这样做不会带来太多麻烦)。
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.
实际上,在Python2.3+中有一种方法可以做到这一点,但这有点深奥。我不知道你是否意识到这一点,但你可以做以下事情:
根据zipimport库:
因此,您只需压缩文件,将zipfile添加到sys.path,然后导入它们。
如果您正在为UNIX构建这个脚本,您也可以考虑使用这个配方打包您的脚本:unix zip executable,但是请注意,如果您计划使用stdin或从sys.args读取任何内容,则可能需要对此进行调整(这样做不会带来太多麻烦)。
根据我的经验,性能不会因此而受到太大的影响,但是在以这种方式导入任何非常大的模块之前,您应该三思而后行。
来自"What’s New in Python 2.6 - Interpreter Changes":
更新2010-11-27:Python 3.2通过引入一个特殊的
__pycache__
子文件夹来解决用.pyc
文件混乱源文件夹的问题,请参见What's New in Python 3.2 - PYC Repository Directories。相关问题 更多 >
编程相关推荐