Python: how to get source code from a code object?

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

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

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

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

Now the problem is: how can I get from Binary, assuming I don't know TheString, a string that represents the original string object?

coming soon: what is the function opposite to compile ()?

+4
source share
1 answer

Without source code, you can only get closer to the code. You can parse the compiled bytecode with dis module , and then restore 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 see that there is 1 line where a function called abs() called with one argument named x . The result is added to another name y , and the result is stored in k .

Projects such as uncompile6 (building on top of many others ) do just that; decompile python bytecode and restore python code.

+11
source

Source: https://habr.com/ru/post/1469502/


All Articles