user1357159
user1357159

Reputation: 319

Checking python syntax of a string in Python?

Lets say I have a string

s="""

print 'hi'
    print 'hi'
print 3333/0
"""

Is there a module or way that can help me check the syntax of this string?

I would like the output to be like:

Line 2, indentation Line 3, Division by Zero

I have heard of pyFlakes, pyChecker and pyLint but those check a file, not a string.

Upvotes: 1

Views: 1324

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

s="""

print 'hi'
    print 'hi'
print 3333/0
"""
eval(s)

output:

Traceback (most recent call last):
  File "prog.py", line 7, in <module>
    eval(s)
  File "<string>", line 3
    print 'hi'
        ^
SyntaxError: invalid syntax

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375574

The compile() function will tell you about compile-time errors:

try:
    compile(s, "bogusfile.py", "exec")
except Exception as e:
    print "Problem: %s" % e

Keep in mind though: one error will prevent the others from being reported, and some of your errors (ZeroDivision) are a run-time error, not something the compiler detects.

Upvotes: 6

Related Questions