The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Fantascape Looping

--

Chapters
00:00 How Can I Check The Syntax Of Python Script Without Executing It?
00:20 Accepted Answer Score 742
00:33 Answer 2 Score 71
00:47 Answer 3 Score 28
01:03 Answer 4 Score 27
01:21 Answer 5 Score 25
01:46 Thank you

--

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

--

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)