python编译、运行、反编译pyc文件 |
您所在的位置:网站首页 › 虚拟机如何运行文件 › python编译、运行、反编译pyc文件 |
简述
Python 并非完全是解释性语言,它也存在编译。先将源码文件 *.py 编译为 *.pyc,然后由 Python 的虚拟机执行。相对于 *.py 文件来说,编译为 *.pyc本质上和 *.py 没有太大区别,只是提高了模块的加载速度,并没有提高代码的执行速度。 *.py:源码文件,由 Python 程序解释。*.pyc:源码经编译后生成的二进制字节码(Bytecode)文件。 生成 *.pyc 文件 方式一:假设,有一个名为 lxk.py 的源文件: print("Hello Python!")要编译为 *.pyc 文件,需要引入 Python 中的模块 py_compile,在交互模式下输入: >>> import py_compile >>> py_compile.compile("lxk.py")这样,*.pyc 文件就生成了: 编译之后的是一个二进制文件,打开: 测试: 命令行下:python -m py_compile test.py 多个文件 import compileall compileall.compile_dir("存放海量py的目录")命令行下:python -m compileall 存放海量py的目录 反编译 pyc 首先安装库 uncompyle: pip install uncompyle 命令行下:uncompyle6 test.pyc > test1.py 关于效率,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 稍占优势。当然,除此之外,还有一个很大的优点:隐藏源码! 这些是 Python 当中较常见的几种形式,其中最常用的是 *.py,因为使用起来比较灵活,可以很容易去修改代码。 注意: Python 3.5 中不再使用 *.pyo 文件,而是引入了一种更灵活的替代机制,*.pyc 文件可以表示优化和未优化的字节码。优化级别信息可以包含在 *.pyc 文件的名字中,具体可参见:PEP 488。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |