compile python .py file without executing

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

> 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

Solution 2 - Python

Yes, there is module compileall. Here's an example that compiles all the .py files in a directory (but not sub-directories):

python -m compileall -l myDirectory

Solution 3 - Python

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.

Solution 4 - Python

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

or

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

Solution 5 - Python

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 ./ ."

Solution 6 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjldupontView Question on Stackoverflow
Solution 1 - PythonRoger PateView Answer on Stackoverflow
Solution 2 - PythonbluszczView Answer on Stackoverflow
Solution 3 - PythonMirko N.View Answer on Stackoverflow
Solution 4 - PythonJavierView Answer on Stackoverflow
Solution 5 - PythonebkView Answer on Stackoverflow
Solution 6 - PythonJensen TaylorView Answer on Stackoverflow