compile python .py file without executing

0 votes
asked Jan 11, 2010 by jldupont

Is there a way to compile a Python .py file from the command-line without executing it?

I am working with an application that stores its python extensions in a non-standard path with limited permissions and I'd like to compile the files during installation. I don't need the overhead of Distutils.

5 Answers

0 votes
answered Jan 11, 2010 by bluszcz

Yes, there is module compileall:

http://docs.python.org/library/compileall.html#module-compileall

Here's an example that compiles all the .py files in a directory (but not sub-directories)

python -m compileall -l myDirectory
0 votes
answered Jan 11, 2010 by javier

$ python -c "import py_compile; py_compile.compile('yourfile.py')"

or

$ python -c "import py_compile; py_compile.compileall('dir')"

0 votes
answered Jan 11, 2010 by mirko-n

In fact if you're on Linux you may already have a /usr/bin/py_compilefiles command in your PATH. It wraps the the py_compile module mentioned by other people. If you're not on Linux, here's the script code.

0 votes
answered Sep 15, 2017 by ebk

In addition to choose the output location of pyc (by @Jensen Taylor's answer), you can also specify a source file name you like for traceback if you don't want the absolute path of py file to be written in the pyc:

python -c "import py_compile; py_compile.compile('src.py', 'dest.pyc', 'whatever_you_like')"

Though "compileall -d destdir" can do the trick too, it will limit your working directory sometimes. For example, if you want source file name in pyc to be "./src.py", you have to move working directory to the folder of src.py, which is undesirable in some cases, then run something like "python -m compileall -d ./ ."

0 votes
answered Sep 15, 2017 by jensen-taylor

I would say something like this, so you can compile it to your chosen location:

import py_compile
py_compile(filename+".py",wantedlocation+wantedname+".pyc")

As I have now done in my Python project on github.com/lolexorg/Lolex-Tools

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...