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

J

Justin Ezequiel

Is there a way to get the original source?
I am trying to retrieve the main script from a py2exe'd old program.
The programmer neglected to commit to SVN before leaving.

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.

PythonWin 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information..... if n.startswith('_'): continue
.... print n
.... a = getattr(c, n)
.... print type(a)
.... print `a`
.... print
....
co_argcount
<type 'int'>
0

co_cellvars
<type 'tuple'>
()

co_code
<type 'str'>
'd\x00\x00d\x01\x00k\x00\x00Z\x00\x00e\x00\x00i\x00\x00\x83\x00\x00GHd\x01\x00S'

co_consts
<type 'tuple'>
(-1, None)

co_filename
<type 'str'>
'foo.py'

co_firstlineno
<type 'int'>
1

co_flags
<type 'int'>
64

co_freevars
<type 'tuple'>
()

co_lnotab
<type 'str'>
'\x0c\x01'

co_name
<type 'str'>
'<module>'

co_names
<type 'tuple'>
('time',)

co_nlocals
<type 'int'>
0

co_stacksize
<type 'int'>
2

co_varnames
 
G

Gregory Ewing

Justin said:
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top