Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 -O file.py didn't create file.pyo

I wrote a simple script test.py, containing:

print('hello')

and then use python -O test.py to run it. I expected this to create a test.pyo file but it did not.

My version is Python 3.5.2. Why was no cache file created?

like image 582
jacin Avatar asked Dec 13 '25 05:12

jacin


1 Answers

Python only creates bytecode cache files for imported modules. The main script (here test.py) is not cached. It doesn't matter what optimisation level is applied.

Import test:

$ python -O -c 'import test'
hello
$ ls __pycache__
test.cpython-35.opt-1.pyc

Note that the cache file was created in a separate directory, named __pycache__, and that the filename is based not only on the module name, but also on the Python version and the optimisation level; use -OO to get .opt-2. As of Python 3.5, the .pyo filename extension is no longer used, see PEP 488 -- Elimination of PYO files, and see PEP 3147 -- PYC Repository Directories as to why a separate directory is used.

If you want to pre-compile your modules, use the python3 -m compileall tool.

like image 160
Martijn Pieters Avatar answered Dec 14 '25 17:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!