Python 文件类型(*.py/*.pyc/*.pyo)
2017-03-29 14:46
316 查看
简述
Python 并非完全是解释性语言,它也存在编译。先将源码文件*.py编译为
*.pyc/*.pyo,然后由 Python 的虚拟机执行。相对于
*.py文件来说,编译为
*.pyc/*.pyo本质上和
*.py没有太大区别,只是提高了模块的加载速度,并没有提高代码的执行速度。
简述
文件类型
生成 pyc 文件
生成 pyo 文件
效率对比
版权所有:一去丶二三里,转载请注明出处:http://blog.csdn.net/liang19890820
文件类型
*.py:源码文件,由 Python 程序解释。
*.pyc:源码经编译后生成的二进制字节码(Bytecode)文件。
*.pyo:优化编译后的程序,也是二进制字节码文件。
生成 *.pyc 文件
假设,有一个名为 hello.py 的源文件:print("Hello World!")
要编译为
*.pyc文件,需要引入 Python 中的模块 py_compile,在交互模式下输入:
>>> import py_compile >>> py_compile.compile("hello.py")
这样,
*.pyc文件就生成了:
$ ls hello.py hello.pyc
编译之后的是一个二进制文件,打开:
生成 *.pyo 文件
要编译为 *.pyo 文件,需要通过 Python 解释器的选项去编译:python -O -m py_compile hello.py
这样,
*.pyo文件就生成了:
$ ls hello.py hello.pyc hello.pyo
由于经过优化,所以,一般在大小上,
*.pyo文件小于等于
*.pyc文件。
效率对比
*.pyc/*.pyo和
*.py文件一样,都可以被执行:
$ python hello.py Hello World! $ python hello.pyc Hello World! $ python hello.pyo Hello World!
关于效率,Python 文档 “Compiled” Python files 中这样介绍:
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.
也就是说,运行速度相差无几,加载速度
*.pyc/*.pyo稍占优势。当然,除此之外,还有一个很大的优点:隐藏源码!
这些是 Python 当中较常见的几种形式,其中最常用的是
*.py,因为使用起来比较灵活,可以很容易去修改代码。
注意: Python 3.5 中不再使用
*.pyo文件,而是引入了一种更灵活的替代机制,
*.pyc文件可以表示优化和未优化的字节码。优化级别信息可以包含在
*.pyc文件的名字中,具体可参见:PEP 488。
相关文章推荐
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python py、pyc、pyo、pyd文件区别
- python下编译py成pyc和pyo
- python 文件 .py .pyc .pyw .pyo .pyd
- python py、pyc、pyo、pyd文件区别
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- Python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- python下编译py成pyc和pyo
- Python基础知识1——py /pyc/pyo
- Python 各种扩展名(py, pyc, pyw, pyo, pyd)区别
- python下编译py成pyc和pyo
- python compile pyc pyo py