120

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?

8
  • @sukhbir: You're right, but I just realized the answer, and it isn't given in that thread. Commented Dec 27, 2010 at 8:23
  • @asmeurer: Yes it is, the answer that you posted is in that question. Commented Dec 27, 2010 at 8:26
  • 2
    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. Commented 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. Commented Dec 27, 2010 at 20:42
  • 2
    Using pylint or pyflakes will find more problems than compiling will. Commented Dec 27, 2010 at 20:46

4 Answers 4

405
python -m py_compile script.py
Sign up to request clarification or add additional context in comments.

3 Comments

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
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().)
This is a great answer, but note there is a similar one python -m compileall some/dir/ that will recurse unlike py_compile.
54

py_compile — Compile Python source files

import py_compile
py_compile.compile('my_script.py')

1 Comment

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.
17

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.

Comments

9

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.