1

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

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

This, or, a bit simpler, ast.parse
@KDawG the parameter mode='exec' does not imply the code being executed. See the docu.
1

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

1 Comment

I'm a huge fan of PyLint but I don't want my small software to depend on it. And it's a bit overkill. Mais merci.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.