Maxime Chéramy
Maxime Chéramy

Reputation: 18841

Checking Python Syntax, in Python

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?

Upvotes: 1

Views: 306

Answers (3)

bereal
bereal

Reputation: 34282

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

Upvotes: 4

user2629998
user2629998

Reputation:

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).

Upvotes: 1

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18841

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.

Upvotes: 1

Related Questions