How To View Compiled Python File

In this tutorial, you will learn how to view a compiled Python file. Compiled Python files are created when the Python interpreter compiles the source code into bytecode, which is then saved in a .pyc file.

These files are used by the interpreter to run your Python programs more efficiently. Let’s take a look at the steps required to view the content of a compiled Python file.

Step 1: Install uncompyle6

To view the content of a compiled Python file, we will use a package called uncompyle6. You can install it using pip by running the following command:

If you have multiple versions of Python installed on your system, make sure to use the appropriate pip command (e.g., pip3 for Python 3) to install the package.

Step 2: Compile your Python file

Before you can view the content of a compiled Python file, you need to compile your source code. In this example, we will use a simple Python script called example.py containing the following code:

To compile your Python file, run the following command:

This will generate a .pyc file inside the pycache directory. The name of the file may vary depending on your Python version, but it should look something like example.cpython-38.pyc.

Step 3: View the content of the compiled file

Now that you have your compiled Python file, it’s time to view its content using uncompyle6. Run the following command:

This command will decompile the .pyc file and save its content as example_decompiled.py. You can now open this file with any text editor to view the content of the compiled Python file.

It is important to note that the content of the decompiled file may not be exactly the same as your original source code. The decompiler will try to generate a readable and functionally equivalent version of the code, but comments, some variable names, and formatting may be lost in the process.

Full Code

Here is the full code we used in this tutorial:

Commands:

Conclusion

In this tutorial, you have learned how to view the content of a compiled Python file using uncompyle6. This can be a helpful tool when you need to examine or reverse-engineer .pyc files but keep in mind that the decompiled code may not be identical to the original source code.