119

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • @sukhbir: You're right, but I just realized the answer, and it isn't given in that thread. – asmeurer Dec 27 '10 at 08:23
  • @asmeurer: Yes it is, the answer that you posted is in that question. – Falmarri Dec 27 '10 at 08: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. – Lennart Regebro Dec 27 '10 at 08: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 Dec 27 '10 at 20:42
  • 2
    Using pylint or pyflakes will find *more* problems than compiling will. – Lennart Regebro Dec 27 '10 at 20:46
  • @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. – asmeurer Dec 28 '10 at 05:07
  • This is true, but also just a matter of time. – Lennart Regebro Dec 28 '10 at 06:54
  • flake8 (https://github.com/pycqa/flake8/blob/master/docs/source/index.rst) – MIkee Jul 29 '19 at 17:00

4 Answers4

400
python -m py_compile script.py
Mark Johnson
  • 14,224
  • 4
  • 28
  • 34
  • 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` – stealthybox Aug 16 '18 at 20:58
  • Documentation: https://docs.python.org/3/using/cmdline.html#using-on-cmdline and https://docs.python.org/3/library/py_compile.html (In particular, see the discussion of `main()`.) – Alan Jan 22 '19 at 14:53
  • This is a great answer, but note there is a similar one `python -m compileall some/dir/` that will recurse unlike `py_compile`. – spagh-eddie Aug 31 '21 at 23:57
54

py_compile — Compile Python source files

import py_compile
py_compile.compile('my_script.py')
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
yurymik
  • 2,194
  • 20
  • 14
  • 7
    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. – erik258 Aug 29 '18 at 19:55
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.

chaim
  • 1,236
  • 2
  • 14
  • 16
pafcu
  • 7,808
  • 12
  • 42
  • 55
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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285