Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile python .py file without executing

Tags:

python

People also ask

How do I compile a .py file?

You can also automatically compile all Python files using the compileall module. You can do it from the shell prompt by running compileall.py and providing the path of the directory containing the Python files to compile: monty@python:~/python$ python -m compileall .

How do I check Python syntax without executing?

You can use these tools: PyChecker. Pyflakes. Pylint.

Do you need to compile Python before running?

pyc file is that Python doesn't have to incur the overhead of compiling it before running it. Since Python would compile to byte-code before running a . py file anyway, there shouldn't be any performance improvement aside from that.


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

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

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.


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

or

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


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