Python 并非完全是解释性语言,它也存在编译。先将源码文件 *.py 编译为 *.pyc,然后由 Python 的虚拟机执行。相对于 *.py 文件来说,编译为 *.pyc本质上和 *.py 没有太大区别,只是提高了模块的加载速度,并没有提高代码的执行速度。
生成 *.pyc 文件
要编译为 *.pyc 文件,需要安装compile模块:
pip install compile
Collecting compile
Downloading compile-1.0.3.tar.gz (6.0 kB)
Building wheels for collected packages: compile
Building wheel for compile (setup.py) ... done
Created wheel for compile: filename=compile-1.0.3-py3-none-any.whl size=6547 sha256=d4ee7be709d3280af20a669a934784c1abe2051797b99ca81eaaef22baf116e2
Stored in directory: c:\users\anonym\appdata\local\pip\cache\wheels\ec\c9\48\b5caf5b67a5ae3bd2dc854aefe766aafeaad244b863792ef32
Successfully built compile
Installing collected packages: compile
Successfully installed compile-1.0.3
生成单个文件
python -m py_compile test.py
生成多个文件
python -m compile all E:\Python\Paddle\PaddleClas\ppcls\modeling\architectures
反编译 pyc
首先安装库 uncompyle:
pip install uncompyle
Collecting uncompyle
Downloading uncompyle-2.0.0-py2.py3-none-any.whl (2.2 kB)
Collecting uncompyle6
Downloading uncompyle6-3.7.4-py3-none-any.whl (316 kB)
|████████████████████████████████| 316 kB 10 kB/s
Collecting spark-parser<1.9.0,>=1.8.9
Downloading spark_parser-1.8.9-py38-none-any.whl (18 kB)
Collecting xdis<5.1.0,>=5.0.4
Downloading xdis-5.0.9-py2.py3-none-any.whl (129 kB)
|████████████████████████████████| 129 kB 1.4 kB/s
Requirement already satisfied: click in c:\program files\python\python38\lib\site-packages (from spark-parser<1.9.0,>=1.8.9->uncompyle6->uncompyle) (8.0.1)
Requirement already satisfied: six>=1.10.0 in c:\program files\python\python38\lib\site-packages (from xdis<5.1.0,>=5.0.4->uncompyle6->uncompyle) (1.16.0)
Requirement already satisfied: colorama in c:\program files\python\python38\lib\site-packages (from click->spark-parser<1.9.0,>=1.8.9->uncompyle6->uncompyle) (0.4.4)
Installing collected packages: xdis, spark-parser, uncompyle6, uncompyle
Successfully installed spark-parser-1.8.9 uncompyle-2.0.0 uncompyle6-3.7.4 xdis-5.0.9
命令行如下:
uncompyle6 .pyc > .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.
也就是说,".py"和"pyc"运行速度相差无几,加载速度 *.pyc 稍占优势。
当然,除此之外,还有一个很大的优点:隐藏源码!