Compile python file to bytecode

Posted on Friday May 5th, 2017

Python executes a script by first compiling it into a bytecode version before actual execution. However, it is possible to compile a python script and retain the bytecode version - which can then be subsequently used when needed, reducing the compile overhead.

The python file - usually with extension .py - will have the resultant bytecode version utilising a .pyc extension. Here's how:

$ python -m compileall foo.py
Compiling foo.py ...

It is also possible to compile all files in a folder:

python -m compileall ./
Listing ./ ...
Compiling ./foo.py ...
Compiling ./foo2.py ...
Compiling ./foo3.py ...

Then running the scripts is simply a case of using the .pyc files:

python foo.pyc

Credit where credit is due:
https://askubuntu.com/questions/324871/how-to-compile-a-python-file