12

i am looking into compiling quite a big set of python modules and packages to pyo. I know this is possible by either setting the PYTHONOPTIMIZE environment variable or by specifying -O on launch. I'd like to enforce pyo instead of pyc to yield the smallest footprint possible. In order to do that in my deploy module i have to create a wrapper script that launches the actual script with the -O option, because the environment variable needs to be specified prior to starting the interpreter.

Is there any way around this and enforce pyo creation programmatically?

Kind regards, Thorsten

instinct-vfx
  • 156
  • 1
  • 1
  • 5

2 Answers2

24

To compile all modules beforehand, run the following command:

python -O -m compileall /path/to/your/files

The python compileall module takes care of the compilation, the -O switch makes it output .pyo files.

However, you cannot force Python to use these unless the -O switch is given for every run or the PYTHONOPTIMIZE environment var is set.

Note that all the -O flag does is disable the assert statement and set the __debug__ flag to False (and Python will optimise out the tests). Specify -OO and docstrings are dropped. These do not make for much speed difference or space savings, unless you used excessive docstring sizes or very slow debug code.

See: What does Python optimization (-O or PYTHONOPTIMIZE) do?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
6

Sadly from version 3.5 the compile optimization only makes .pyc files, not .pyo

Changed in version 3.5: The legacy parameter only writes out .pyc files, not .pyo files no matter what the value of optimize is.

From https://docs.python.org/3.6/library/compileall.html