Compile (but do not run) a Python script [duplicate]
Asked Answered
A

4

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?

Aeon answered 27/12, 2010 at 8:15 Comment(8)
@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
C
54

py_compile — Compile Python source files

import py_compile
py_compile.compile('my_script.py')
Canvas answered 27/12, 2010 at 8:23 Comment(1)
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
K
402
python -m py_compile script.py
Kendry answered 8/12, 2011 at 20:56 Comment(3)
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_compilePetcock
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
C
54

py_compile — Compile Python source files

import py_compile
py_compile.compile('my_script.py')
Canvas answered 27/12, 2010 at 8:23 Comment(1)
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
B
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.

Bartram answered 27/12, 2010 at 8:28 Comment(0)
E
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.

Ehr answered 27/12, 2010 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.