python之pyc 和 pyo

Python 在解释源码程序时分为两步:

第一步: 将源码(*.py) 转为 字节码(*.pyc);
第二步:将字节码 转换为 机器码。

*.py文件:源码文件,由python程序解释。

*.pyc文件:是python编译后的字节码(bytecode)文件。只要你运行了py文件,python编译器就会自动生成一个对应的pyc字节码文件。这个pyc字节码文件,经过python解释器,会生成机器码运行(这也是为什么pyc文件可以跨平台部署,类似于java的跨平台,java中JVM运行的字节码文件)。下次调用直接调用pyc,而不调用py文件。直到你这个py文件有改变。python解释器会检查pyc文件中的生成时间,对比py文件的修改时间,如果py更新,那么就生成新的pyc。
(pyc ,py代码python,c是 compile 的含义,pyc即编译过的python 文件)

*.pyo文件:是python编译优化后的字节码文件。pyo文件在大小上,一般小于等于pyc文件。如果想得到某个py文件的pyo文件,可以这样:

    python -O -m py_compile xxxx.py
    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.
————————————————
版权声明:本文为CSDN博主「常城」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/chenggong2dm/article/details/11606405

原文地址:https://www.cnblogs.com/hq1015/p/15065537.html