retrieve source code from code object as returned by compile()

Gregory Ewing greg.ewing at canterbury.ac.nz
Thu Apr 24 01:53:38 EDT 2014


Justin Ezequiel wrote:
> Using "Easy Python Decompiler" I am able to get the source for the imported
> modules. Using "Resources Viewer" from PlexData and some code I am able to
> retrieve the code object. I am however stumped as to how to retrieve the
> source from this code object.

Easy Python Decompiler should be able to do that, but you
may need to delve into its innards a bit to find an entry
point where you can feed in a code object.

Alternatively you could create a .pyc file out of the code
object and then use Easy Python Decompiler on that. The
following snippet of code should do that:

import marshal
import py_compile
import time

with open('output.pyc', 'wb') as fc:
     fc.write('\0\0\0\0')
     py_compile.wr_long(fc, long(time.time()))
     marshal.dump(codeobject, fc)
     fc.flush()
     fc.seek(0, 0)
     fc.write(py_compile.MAGIC)

(Taken from: 
http://stackoverflow.com/questions/8627835/generate-pyc-from-python-ast)

-- 
Greg



More information about the Python-list mailing list