Python Compiled Files (.pyc) are binary files generated by Python when a script is executed. These files contain the compiled bytecode, which helps Python run programs faster by skipping the compilation step on subsequent runs. When you import a module, Python automatically creates a .pyc file in the __pycache__ directory, storing the bytecode for future use.

What is a PYC File?

A .pyc file is the result of compiling a Python source file (.py). Instead of running the source code every time, Python can execute the bytecode stored in the .pyc file, improving performance. The .pyc file is specific to the Python version that created it, so running it with a different version may cause errors.

Structure of a PYC File

  • Magic Number: Identifies the Python version.
  • Flags/Hash: Indicates how the file was created and if it is hash-based.
  • Timestamp/Size: Shows when the source was last modified and its size.
  • Bytecode: The actual compiled instructions for the Python interpreter.

Security Considerations

While .pyc files hide the source code, they can still be decompiled. Tools like decompyle3 can reconstruct readable Python code from bytecode. For true security, consider additional obfuscation or packaging methods.

Tool Highlight: show.py

The show.py script is a utility for inspecting .pyc files. It displays metadata such as the magic number, flags, modification date, and the structure of the bytecode. This is useful for debugging or learning about Python internals.

Common PYC File Operations

Check Python Version of a .pyc File

1
file main.pyc

Run a .pyc File

1
python main.pyc

Show Info About a .pyc File

1
python show.py main.pyc

Decompile a .pyc File

1
decompyle3 main.pyc

Install decompyle3

1
pip install decompyle3

Summary

PYC files are a core part of Python’s execution model, enabling faster program startup and simple code distribution. However, they are not a substitute for true code protection. With tools like show.py and decompyle3, you can inspect and decompile bytecode, making .pyc files a useful but not entirely secure way to share Python programs.