The Python Oracle

How can I check the syntax of Python script without executing it?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:25 Accepted answer (Score 710)
00:38 Answer 2 (Score 71)
00:51 Answer 3 (Score 28)
01:09 Answer 4 (Score 23)
01:38 Thank you

--

Full question
https://stackoverflow.com/questions/4284...

Answer 1 links:
[PyChecker]: http://pychecker.sourceforge.net/
[Pyflakes]: https://github.com/pyflakes/pyflakes
[Pylint]: http://www.logilab.org/857

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #compilation #syntaxchecking

#avk47



ACCEPTED ANSWER

Score 747


You can check the syntax by compiling it:

python -m py_compile script.py



ANSWER 2

Score 71


You can use these tools:




ANSWER 3

Score 28


import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')

Save this as checker.py and run python checker.py yourpyfile.py.




ANSWER 4

Score 28


Here's another solution, using the ast module:

python -c "import ast; ast.parse(open('programfile').read())"

To do it cleanly from within a Python script:

import ast, traceback

filename = 'programfile'
with open(filename) as f:
    source = f.read()
valid = True
try:
    ast.parse(source)
except SyntaxError:
    valid = False
    traceback.print_exc()  # Remove to silence any errros
print(valid)