Odds and Ends

Decompiling Python .pyc Files

Have you accidentally deleted an important Python source file or are looking to inspect the contents of a .pyc file that has been provided to you? Luckily .pyc files contain enough information to reproduce the corresponding .py file. NB: this only applies to Python2. You won’t get the original comments or the original formatting, and there may be a few tweaks you need to do for the new .py file to be completely valid–but this can be a savior for some unexpected loss of source files if the .pyc files still exist.

The best way I have found to do this is pycdc (you can find the github here).

To build the C++ executables do the following steps. You must have cmake installed.

git clone https://github.com/zrax/pycdc.git
cd pycdc
cmake .
make

Once pycdc is built you can use it in the following manner to produce a .py file from a .pyc file:

path/to/pycdc path/to/file_of_interest.pyc > file_of_interest.py

In cases where I have functions that accept arbitrary keyword arguments with **kwargs and pass those on to subsequent functions in the same way, I have to convert **None syntax back to **kwargs within the decompiled Python code.

# Decompiled output
def myfunc(**kwargs):
    result = otherfunc(**None)
    return result

# Should be changed to
def myfunc(**kwargs):
    result = otherfunc(**kwargs)
    return result
Tags: decompile pycdc py2 pyc