关于 python中的.pyc 文件

.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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值