6

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

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

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

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

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

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

Alberto Perrella
  • 1,318
  • 5
  • 12
  • 19

1 Answers1

16

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    `unpyc` and `uncompyle2` look super old (7 years, 9 years) respectively. Do you know if there's anything more... modern? Which also supports Python3? -- Nevermind.. found it: https://pypi.python.org/pypi/uncompyle6 – exhuma Apr 05 '18 at 09:42
  • @exhuma: this answer is pretty old too, at 5 years and counting ;-) Yes, the various decompilation packages have been morphing and changing over the years, I'll update. – Martijn Pieters Apr 05 '18 at 20:42
  • @exhuma - [This answer](https://stackoverflow.com/questions/5287253/is-it-possible-to-decompile-a-compiled-pyc-file-into-a-py-file/14808336#14808336) mentions Uncompyle6: – RichVel Oct 30 '18 at 15:26