This is for my test suite.
I have an automatically-generated Python package in a temporary folder. It's all .py
files. I want to programmatically compile these into (a) .pyc
and (b) .pyo
files. (One test will do .pyc
, another will do .pyo
.) This should be done with the active interpreter, of course. I do not want to import the modules, just compile.
How can I do this?
In your Python lib directory, there will be a script called compileall.py
(e.g., /usr/lib/python2.6/compileall.py
).
In your code, spawn (e.g., by using os.spawnl
) an invocation of compileall.py
pointed at the directory containing your generated code. If you invoke it using python -O
it will generate .pyo
files; if you invoke it using python
it will generate .pyc
file.
The trick, I suppose, would be to call with the right version of the Python interpreter.
compileall.py
uses py_compile
under the hood.