Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python - pycompile for python3.2

I am running mint 13 and have python 3.2 installed using the apt-get package management system. I also have python 2.7 installed along with 3.2 The pycompile seems to be the one that packages python 2.7 code and and throws exceptions for python 3.2 code.

I have looked around and tried to install a few packages, but have not been able to find pycompile for python 3.2. How do I get pycompile work for python 3.2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...