为什么 Python 只保存导入脚本的字节码?

Why does Python only save the bytecode for a script if it is imported?

既然执行Python字节码会比运行原始源码快,因为Python不用重新编译,为什么Python只保存编译后的导入脚本时的字节码?为每个执行的脚本保存 .pyc 文件不是更好吗?

你的 Python 解释器的启动时间无论如何都需要时间(即使你可能没有注意到那么多),所以它根本不重要而且启动一个可能有的脚本更方便由您更新,而不是总是手动编译和执行脚本。

be faster than running the original source code

顺便说一句,Python 没有 'run' 来源。来自主脚本的初始源代码也被编译和执行。

另请注意(Introduction to Python):

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

他们还说:

When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

你可以随时测试它。这是我机器上的一段轶事:

~$ time python test.py
real    0m0.029s
user    0m0.025s
sys     0m0.004s
~$ time python test.pyc

real    0m0.031s
user    0m0.025s
sys     0m0.004s