.py源文件在执行时会首先被编译成.pyc(compiled py)文件,.pyc文件中存放着byte code,可以直接被PVM(The Python Virtual Machine )执行。
如果pyc文件存在,那么下次执行相应的py文件时,会直接执行pyc文件,执行速度较第一次执行py文件时会快一些。
借用learning python一书中的描述:
Byte code is the lower-level form of your program after Python compiles it.
Python automatically stores byte code in files with a .pyc extension.
Python saves byte code like this as a startup speed optimization. The next time you run
your program, Python will load the .pyc files and skip the compilation step, as long as
you haven’t changed your source code since the byte code was last saved.
The PVM is the Python Virtual Machine—the runtime engine of Python that interprets
your compiled byte code.
If Python cannot write the byte code files to your machine, your program still works—
the byte code is generated in memory and simply discarded on program exit.* However,
because .pyc files speed startup time, you’ll want to make sure they are written for larger
programs. Byte code files are also one way to ship Python programs—Python is happy
to run a program if all it can find are .pyc files, even if the original .py source files are
absent.
为什么我们直接双击py文件运行时,很难找到相应的pyc文件产生呢?
目前也不是很清楚,可能是因为pyc属于一种中间内部文件,在执行完毕之后,会被自动删除吧。
但是有几种方法可以显示的生成pyc文件:
1. 通过python的交互式方式
import py_compile
py_compile.compile(file.fy)
2. 通过command line的方式
python -m py_compile file.py
python -O -m py_compile file.py (生成的是pyo文件,是pyc文件的一种优化)
其中-m相当于import 某一个module