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?
-
@sukhbir: You're right, but I just realized the answer, and it isn't given in that thread.asmeurer– asmeurer2010-12-27 08:23:24 +00:00Commented Dec 27, 2010 at 8:23
-
@asmeurer: Yes it is, the answer that you posted is in that question.Falmarri– Falmarri2010-12-27 08:26:33 +00:00Commented Dec 27, 2010 at 8:26
-
2Compiling 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.Lennart Regebro– Lennart Regebro2010-12-27 08:44:47 +00:00Commented Dec 27, 2010 at 8:44
-
@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.asmeurer– asmeurer2010-12-27 20:42:56 +00:00Commented Dec 27, 2010 at 20:42
-
2Using pylint or pyflakes will find more problems than compiling will.Lennart Regebro– Lennart Regebro2010-12-27 20:46:18 +00:00Commented Dec 27, 2010 at 20:46
|
Show 3 more comments
4 Answers
python -m py_compile script.py
3 Comments
stealthybox
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_compileAlan
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().)spagh-eddie
This is a great answer, but note there is a similar one
python -m compileall some/dir/ that will recurse unlike py_compile.py_compile — Compile Python source files
import py_compile
py_compile.compile('my_script.py')
1 Comment
erik258
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.
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.