As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-``byte-compiled'' version of the module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don't match.
对于引用了大量标准模块的短程序,有一个提高启动速度的重要方法,如果在 spam.py 所在的目录下存在一个名为 spam.pyc 的文件,它会被视为 spam 模块的预“编译”(``byte-compiled'' ,二进制编译)版本。用于创建 spam.pyc 的这一版 spam.py 的修改时间记录在 spam.pyc文件中,如果两者不匹配,.pyc 文件就被忽略。
Normally, you don't need to do anything to create the spam.pyc file. Whenever spam.py is successfully compiled, an attempt is made to write the compiled version to spam.pyc. It is not an error if this attempt fails; if for any reason the file is not written completely, the resulting spam.pyc file will be recognized as invalid and thus ignored later. The contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures.
通常你不需要为创建 spam.pyc 文件做任何工作。一旦 spam.py 成功编译,就会试图编译对应版本的 spam.pyc 。如果有任何原因导致写入不成功,返回的 spam.pyc 文件就会视为无效,随后即被忽略。 spam.pyc 文件的内容是平台独立的,所以Python模块目录可以在不同架构的机器之间共享。
Some tips for experts:
部分高级技巧:
.pyc
files are ignored and .py
files are compiled to optimized bytecode.
以 -O 参数调用Python解释器时,会生成优化代码并保存在
.pyo
文件中。现在的优化器没有太多帮助;它只是删除了断言(assert
)语句。使用 -O 参参数,所有的代码都会被优化;
.pyc
文件被忽略, .py
文件被编译为优化代码。
__doc__
strings are removed from the
bytecode, resulting in more compact .pyo files. Since some
programs may rely on having these available, you should only use this
option if you know what you're doing.
向Python解释器传递两个 -O
参数(-OO)会执行完全优化的二进制优化编译,这偶尔会生成错误的程序。现在的优化器,只是从二进制代码中删除了
__doc__
符串,生成更为紧凑的 .pyo
文件。因为某些程序依赖于这些变量的可用性,你应该只在确定无误的场合使用这一选项。
来自 .pyc 文件或 .pyo 文件中的程序不会比来自 .py 文件的运行更快; .pyc 或 .pyo 文件只是在它们加载的时候更快一些。
通过脚本名在命令行运行脚本时,不会将为该脚本创建的二进制代码写入 .pyc 或.pyo 文件。当然,把脚本的主要代码移进一个模块里,然后用一个小的解构脚本导入这个模块,就可以提高脚本的启动速度。也可以直接在命令行中指定一个 .pyc 或 .pyo 文件。
对于同一个模块(这里指例程 spam.py --译者),可以只有 spam.pyc 文件(或者 spam.pyc ,在使用 -O 参数时)而没有 spam.py 文件。这样可以打包发布比较难于逆向工程的Python代码库。
compileall 模块 可以为指定目录中的所有模块创建 .pyc 文件(或者使用 .pyo 参数创建.pyo文件)。