restore sources from PYC [Q]

Michael Hudson mwh21 at cam.ac.uk
Fri Apr 16 02:54:10 EDT 1999


"Bruno Mattarollo" <brunomadv at ciudad.com.ar> writes:
> Hi!
> 
> 	By mistake I am unable to find the PY files (source) from a project I was
> working on. I only have the PYC files... Is there a way to recover the
> sources from the PYC? I only need my sources, I don't give a d... for the
> comments...

Well.... The pyc files are marshalled code objects (after an eight
byte header), and there's the standard module dis which can
disassemble code objects, from which you could have a stab at
rewriting your code. You certainly wouldn't *want* to do it this way.

It would probably be within the bounds of possibility to write a
decompiler, though unless you've lost a vast heap of code this is
going to be a much bigger project than rewriting your code.

Anyway, if it helps, here's a function that'll pull the code out of a
.pyc file and disassemble that code: 

def dis_pyc(pyc_name):
    import marshal,dis
    file=open(pyc_name,'rb')
    file.read(8)
    code=marshal.load(file)
    did.dis(code)

(NB: This isn't much use because defined functions and classes are in
their own code objects stored as constants - they're still accessible,
in code.co_consts, but this code doesn't go looking for them)
 
> 	TIA
> 
> /B
> 
> Bruno Mattarollo <bruno at gaiasur.com.ar>
> ... proud to be a PSA member <http://www.python.org/psa>

Good luck!

Michael




More information about the Python-list mailing list