I would like to know if it's possible to check if a Python code has a correct syntax, without running it, and from a Python program. The source code could be in a file or better in a variable.
The application is the following: I have a simple text editor, embedded in my application, used for editing Python scripts. And I'd like to add warnings when the syntax is not correct.
My current idea would be to try importing the file and catch a SyntaxError exception that would contains the erroneous line. But I don't want it to execute at all. Any idea?
3 Answers 3
That's the job for ast.parse:
>>> import ast
>>> ast.parse('print 1') # does not execute
<_ast.Module at 0x222af10>
>>> ast.parse('garbage(')
File "<unknown>", line 1
garbage(
^
SyntaxError: unexpected EOF while parsing
Comments
I just found out that I could probably use the compile function. But I'm open to better suggestions.
import sys
# filename is the path of my source.
source = open(filename, 'r').read() + '\n'
try:
compile(source, filename, 'exec')
except SyntaxError as e:
# do stuff.
2 Comments
mode='exec' does not imply the code being executed. See the docu.You could use PyLint and call it when the file is saved, and it'll check that file for errors (it can detect much more than just syntax errors, look at the documentation).