py_compile
is a stdlib module that can produce byte-code given Python source. It is rarely needed.
To compile Python 3 source code you must use py_compile version included with it and not the version from Python 2.7 if you use it from a command-line:
$ python3 -mpy_compile your_script.py
To change the default location where pyc-files are stored you could use cfile
parameter of the py_compile.compile()
function.
Does the byte code make the script run any faster?
It might (by a minuscule amount). Python compiler doesn't do much so it is fast.
Here's an example how byte-code looks like in a human readable form:
>>> def f(o):
... with o:
... pass
...
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (o)
3 SETUP_WITH 5 (to 11)
6 POP_TOP
3 7 POP_BLOCK
8 LOAD_CONST 0 (None)
>> 11 WITH_CLEANUP
12 END_FINALLY
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
All heavy lifting is left for the python interpreter that interprets the byte-code at runtime.
Or is this only for distribution?
The docs provide a use-case: a shared directory with Python modules where only curtain users can write. You can disable caching byte-code to disk so it is possible to use py-files that stored in read-only locations without corresponding pyc-files.
Why is it rarely used?
Usually the pyc-files are created by building/installation process. If there is no pyc-files they can be created on-the-fly when you import a module:
$ python -c 'import some_module'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…