Python:如何从代码对象获取源代码? [英] python: how to get the source from a code object?

查看:158
本文介绍了Python:如何从代码对象获取源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个python字符串(不是文件,一个字符串,没有文件)

let's suppose we have a python string(not a file,a string,no files)

TheString = "k=abs(x)+y"

好吗?现在我们将字符串编译成一段python字节码

ok? Now we compile the string into a piece of python bytecode

Binary = compile( TheString , "<string>" , "exec" )

现在的问题是:假设我不知道TheString,我该如何从Binary获取数据,

now the problem: how can i get from Binary , supposing i don't know TheString , a string that represents the original string object?

很快:与compile()相反的函数是什么?

shortly: what is the function that is opposite to compile() ?

推荐答案

没有源代码,您只能近似代码。您可以使用 反汇编已编译的字节码。 > dis 模块,然后将源代码重构为近似值:

Without the source code, you can only approximate the code. You can disassemble the compiled bytecode with the dis module, then reconstruct the source code as an approximation:

>>> import dis
>>> TheString = "k=abs(x)+y"
>>> Binary = compile( TheString , "<string>" , "exec" )
>>> dis.dis(Binary)
  1           0 LOAD_NAME                0 (abs)
              3 LOAD_NAME                1 (x)
              6 CALL_FUNCTION            1
              9 LOAD_NAME                2 (y)
             12 BINARY_ADD          
             13 STORE_NAME               3 (k)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE        

从反汇编中我们可以看到只有1行,其中调用了名为 abs()的函数,并带有一个名为 x的参数。 。结果被添加到另一个名称 y ,结果存储在 k 中。

From the disassembly we can see there was 1 line, where a function named abs() is being called with one argument named x. The result is added to another name y, and the result is stored in k.

> $$$ c> uncompile6 这样的项目(在其他许多人的工作之上构建 )做到这一点;反编译python字节码并从中重建Python代码。

Projects like uncompile6 (building on top of the work of many others) do just that; decompile the python bytecode and reconstruct Python code from that.

这篇关于Python:如何从代码对象获取源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆