tags:

views:

144

answers:

4

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.

+3  A: 

The py_compile module provides a function to generate a byte-code file from a source file, and another function used when the module source file is invoked as a script.

python -m py_compile fileA.py fileB.py fileC.py
Roger Pate
@Roger: sounds good... thanks!
jldupont
A: 

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

or

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

Javier Badia
hmmm... the solution proposed by @Roger Pate appears cleanly but thanks.
jldupont
+1  A: 

Yes, there is module compileall:

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

bluszcz
have you read the question?
jldupont
Why be snotty? compileall seems to do just what you want. If there's a detail he missed, why not point it out to him?
Ned Batchelder
+1  A: 

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.

Mirko Nasato
+1 for the interesting info but I'd rather not rely on this script being present (or not).
jldupont