← Go Back

How to Compile a Python File

Running the following command in the terminal:

python -m compileall file.py

Where file.py is the name or path of the file you want to compile. This will generate a new folder called __pycache__, inside which the compiled file with a .pyc extension will be found. Instead of a file name, a folder can be specified so that all Python files contained therein can be compiled.

Note that Python can only compile .py to .pyc files, which still require the interpreter to be executed. For example:

cd __pycache__
python file.python312.pyc

Files compiled with one version of Python cannot be executed by an interpreter of another version.

To generate an executable file (for example, a .exe file on Windows) that does not require a Python interpreter to be executed, see Create Executable File With PyInstaller, cx_Freeze, py2exe.


🐍 You might also find interesting: