1

If I import a module1.py from the python command line in windows 7 I see the corresponding module1.pyc file appear in the Python32/pycache/ folder. My understanding was that it is this bytecode which is executed by the Python interpreter, however I can delete the module1.pyc file and my module functions (module1.func1() etc...) can still be called from the command line. What is running when the functions are called but the .pyc file is not there? When the bytecode is compiled is it also copied to runtime memory for the Python shell?

4

2 回答 2

5

运行解释器时字节码在内存中。.pyc 文件是下一次导入代码的缓存,因此如果代码没有更改,python 将不必解析代码。

于 2012-05-28T13:03:07.033 回答
4

TL;博士

Python 总是运行编译后的字节码,要么在运行时编译,要么从磁盘上的 .pyc 文件中读取。

稍微长一点的答案

当需要编译字节码时,Python 会调用py_compilecompileall 。如果在 .pyc 文件中找到有效的预编译字节码,Python 会使用它。即使没有原始源文件,它也可以做到这一点。

如果没有 .pyc 文件,或者源文件比预编译的字节码新,那么 Python 将使用源文件并重新编译。这就是你观察到的行为。

官方答复

有关规范的答案,请参阅PEP 3147:PYC 存储库目录

于 2012-05-28T13:32:04.483 回答