pyc文件是做什么的

准备工作

新建三个文件 start.py test1.py test2.py

其中,start.py里面import了test1和test2,并且print ‘this is start.py’

test1.py里面print ‘this is test1.py’

test2.py里面print ‘this is test2.py’

执行python start.py

zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ ls
start.py  test1.py  test2.py
zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ python start.py
this is test1.py
this is test2.py
this is start.py
zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ ls
start.py  test1.py  test1.pyc  test2.py  test2.pyc
zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$

生成pyc

从上面的代码可以看到,执行了start.py之后,
多生成了两个pyc文件,分别是test1.pyc和test2.pyc

为什么会生成这两个文件呢?
为什么只生成这两个文件呢?start.pyc呢?

原理

python在执行代码的时候,会先由解释器将代码解释为PyCodeObject对象,俗称字节码(byte code),之后python编译器才能执行字节码(注意,字节码才是可执行的)

众所周知python运行效率是比编译性语言,例如C++和java慢的。因此他将解释器生成的字节码存在硬盘里,下次运行的时候直接使用字节码,就省去了解释的过程,性能就得到提高了。

事实上pyc是可以直接执行的,我们像刚刚一样,执行一下pyc文件试试

zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ ls
start.py  test1.py  test1.pyc  test2.py  test2.pyc
zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ python test1.pyc
this is test1.py

什么时候会生成pyc文件

刚刚的疑问我们只解决了第一个,那为什么start.pyc没有生成呢

原因是python会在某个模块被import的时候生成pyc文件,start.py没有被import,自然就没有生成pyc文件

如果希望所有的文件都生成pyc文件,可以这么做

zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$ python -m compileall .
Listing . ...
Compiling ./start.py ...
zhangqixiang@g37-dev-c3404c16:~/pythonzqx/learn/pyc_learn$

执行python -m compileall .

这会将当前目录下所有Python文件生成Pyc文件

什么时候更新pyc文件

事实上,当你从入口函数开始执行的时候,并不是所有代码都发生了修改。如果上一次pyc文件的修改时间,晚于对应python文件的修改时间,那么pyc将不会重新解释生成。反之,则需要重新解释成字节码替换原pyc文件。

猜你喜欢

转载自blog.csdn.net/qq_37768971/article/details/118493091