问题描述
我一直在使用 dis
库来反汇编一些Python源代码,但是我发现这并没有递归为函数或类:
I have been playing with the dis
library to disassemble some Python source code, but I see that this does not recurse into functions or classes:
import dis
source_py = "test.py"
with open(source_py) as f_source:
source_code = f_source.read()
byte_code = compile(source_code, source_py, "exec")
dis.dis(byte_code)
我所看到的都是以下条目:
All I see are entries such as:
54 456 LOAD_CONST 63 (<code object foo at 022C9458, file "test.py", line 54>)
459 MAKE_FUNCTION 0
462 STORE_NAME 20 (foo)
如果源文件具有功能 foo()
,我显然可以在源文件中添加以下内容:
If the source file had a function foo()
, I could obviously add something like the following to the sourcefile:
dis.dis(foo)
我不知道如何在不更改源文件的情况下执行此操作并执行它。我希望能够从编译后的 byte_code
中提取相关的字节,并将其传递给 dis.dis()
I cannot figure out how to do this without changing the source file and executing it. I would like to be able to extract the pertinent bytes from the compiled byte_code
and pass them to dis.dis()
.
def sub_byte_code(byte_code, function_or_class_name):
sub_byte_code = xxxxxx
dis.dis(sub_byte_code)
我已经考虑过包装源代码并执行 dis.dis()
如下,但我不想执行该脚本:
I have considered wrapping the source code and executing dis.dis()
as follows but I do not wish to execute the script:
source_code_dis = "import dis\n%s\ndis.dis(foo)\n" % (source_code)
exec(source_code_dis)
也许有把戏吗?例如 dis.dis(byte_code,recurse = True)
推荐答案
导入文件作为模块,然后在该模块上调用 dis.dis()
。
Import the file as a module and call dis.dis()
on that module.
import dis
import test
dis.dis(test)
您也可以从命令行执行此操作:
You can also do this from the command-line:
python -m dis test.py
引用的文档:
Quoting from the documentation for dis.dis
:
编辑:从python 3.7开始, dis.dis
是递归的。
Edit: As of python 3.7, dis.dis
is recursive.
这篇关于如何完全反汇编Python源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!