python: how to get the source from a code object? [duplicate]

China☆狼群 提交于 2019-12-01 05:34:57

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        

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!