Python编译、运行、反编译pyc文件

本文探讨了Python的编译过程,如何通过compile模块将.py转换为.pyc以加快模块加载速度,同时介绍了uncompyle用于反编译pyc文件及其效率分析。重点突出了隐藏源码和加载速度提升的优点。
摘要由CSDN通过智能技术生成

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 稍占优势。

当然,除此之外,还有一个很大的优点:隐藏源码!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值