19

Lets say I have:

>>> def test(a):    
>>>    print a

Now, I want to explore see how test looks like in its compiled form.

>>> test.func_code.co_code
'|\x00\x00GHd\x00\x00S'

I can get the disassembled form using the dis module:

>>> import dis
>>> dis.dis(test)
  2           0 LOAD_FAST                0 (a)
              3 PRINT_ITEM
              4 PRINT_NEWLINE
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

Is there an opensource and maintained decompiler I could use to turn the bytecode back into readable python code?

update: thanks for suggesting decompile, but it's outdated (python2.3) and no one maintains it anymore. Is there anything for python2.5 or later?

rocky
  • 7,226
  • 3
  • 33
  • 74

6 Answers6

6

UnPyc

http://sourceforge.net/projects/unpyc/

It is a maintained fork of the old decompyle updated to work with 2.5 and 2.6.

  • 5
    From the project's readme.txt: "D - decompile (not implemented yet)". So no, this is a poor substitute for decompyle. – Cerin Feb 03 '10 at 16:12
5

get uncompyle2 from github! :)

nokarmawhore
  • 59
  • 1
  • 1
5

There is also now uncompyle6 and the more narrow decompyle3 (for Python 3.7 and 3.8 and is not packaged). Both of these are written in Python. Also there is pycdc written in C++.

These handle several versions of Python bytecode starting from Python 1 and going to Python 3 versions, except where noted above.

Another thing you might consider is a bytecode interpreter which allows you to trace and/or step bytecode instructions.

For this there is x-python for the interpreter and trepanxpy the gdb-like debugger for that. See the links for the Python bytecode versions that are interpreted and for which Python versions are needed to run the interpreter.

rocky
  • 7,226
  • 3
  • 33
  • 74
2

decompyle

Decompyle is a python disassembler and decompiler which converts Python byte-code (.pyc or .pyo) back into equivalent Python source. Verification of the produced code (re-compiled) is avaliable as well.

Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87
2

Uncompyle2 worked for me with Python 2.7.

https://github.com/wibiti/uncompyle2

Quick how to use uncompyle2 , Install it and then

>>>import uncompyle2
>>> with open("decompiled.py","wb") as f:
...   uncompyle2.uncompyle_file("compiled.pyc",f)

It will generate source code back in decompile.py

DevC
  • 7,055
  • 9
  • 39
  • 58
1

In addition to what DevC wrote:

  1. Uncompyle2 works with Python 2.7

  2. with Uncompyle2, you can also un-compile from the command line:

    $ uncompyle2 compiled.pyc >> source.uncompyle2.py

  3. to install Uncompyle2, do

    $ git clone https://github.com/wibiti/uncompyle2

    $ cd uncompyle2

    $ sudo ./setup.py install

Maxim
  • 221
  • 2
  • 4