把一个py文件编译为pyc文件了。(假设在windows环境下)
import py_compile
py_compile.compile(r'H:\game\test.py')
py_compile.compile('webmail_sina.py') # Linux环境
批量生成pyc文件
>>> import compileall
>>> compileall.compile_dir(r'/home/codemo/Desktop/python')
python -O -m py_compile test.py 生成 test.pyo
python -m py_compile test.py 生成test.pyc
pyc文件,是Python编译后的字节码(bytecode)文件。只要你运行了py文件,python编译器就会自动生成一个对应的pyc字节码文件。
这个pyc字节码文件,经过python解释器,会生成机器码运行(这也是为什么pyc文件可以跨平台部署,类似于Java的跨平台,java中JVM运行的字节码文件)
。下次调用直接调用pyc,而不调用py文件。直到你这个py文件有改变。python解释器会检查pyc文件中的生成时间,对比py文件的修改时间,如果py更新,那么就生成新的pyc。
pyo文件,是python编译优化后的字节码文件。pyo文件在大小上,一般小于等于pyc文件。
python文档是这样描述的:这个优化没有多大作用,只是移除了断言。
原文如下:
When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in .pyo files.
The optimizer currently doesn’t help much; it only removes assert statements.
When -O is used, all bytecode is optimized;
.pyc files are ignored and .py files are compiled to optimized bytecode.
至于速度,运行几乎一样,加载pyc和pyo稍占优势。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.