I want to check a script for syntax errors. In both 2.x and 3.x, how can I compile the script without running it?
Compile (but do not run) a Python script [duplicate]
Asked Answered
@sukhbir: You're right, but I just realized the answer, and it isn't given in that thread. –
Aeon
@asmeurer: Yes it is, the answer that you posted is in that question. –
Karachi
Compiling and syntax checking are different things, really. You want to syntax check, The answer is in the other thread. You ask how to compile it, which is a different question, you should really change the topic. –
Tautologize
@Lennart: Is there a way to check syntax without compiling? I suppose you could use something like pylint, but in Python compiling is such a fast operation that you might as well do that and make truly sure that everything works. –
Aeon
Using pylint or pyflakes will find more problems than compiling will. –
Tautologize
@Lennart: Unfortunately, Pylint/Pyflakes currently do not satisfy one of the conditions of my original question, which is that it must run in Python 3. –
Aeon
This is true, but also just a matter of time. –
Tautologize
flake8 (github.com/pycqa/flake8/blob/master/docs/source/index.rst) –
Coadjutrix
py_compile — Compile Python source files
import py_compile
py_compile.compile('my_script.py')
Before you use this approach, take a look at Mark Johnson's highly voted answer to make this a command-line execution without additional python. –
Apostasy
python -m py_compile script.py
You can expand on this with
find
and xargs
to check directories. Here's how to run it on your src/
dir: find src -type f -name '*.py' | xargs -n1 python3 -m py_compile
–
Petcock Documentation: docs.python.org/3/using/cmdline.html#using-on-cmdline and docs.python.org/3/library/py_compile.html (In particular, see the discussion of
main()
.) –
Rainfall This is a great answer, but note there is a similar one
python -m compileall some/dir/
that will recurse unlike py_compile
. –
Hamadryad py_compile — Compile Python source files
import py_compile
py_compile.compile('my_script.py')
Before you use this approach, take a look at Mark Johnson's highly voted answer to make this a command-line execution without additional python. –
Apostasy
You can use pylint to find syntax errors as well as more subtle errors, such as accessing undefined variables in some rarely-used conditional branch.
One way is to do something like this (for test.py
):
python -c "__import__('compiler').parse(open('test.py').read())"
This works for Python 2.x.
© 2022 - 2024 — McMap. All rights reserved.