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.
asked Jun 13, 2012 at 0:59
user1357159
3191 gold badge6 silver badges19 bronze badges
2 Answers 2
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.
answered Jun 13, 2012 at 1:04
Ned Batchelder
378k77 gold badges583 silver badges675 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
user1357159
Hmm, yeah, but I was hoping to stay away from file IO
Ned Batchelder
There's no file I/O here... "bogusfile.py" is just a name for the compiler to use as the file name. Perhaps you could tell us more about the whole problem you're trying to solve?
user1357159
Hmm, I was hoping that it could give me errors including Division by Zero, maybe using execfile but using a string (if possible) and changing the namespace would work? I dont know, also I was hoping that it would display all the errors
Karl Knechtel
"division by zero" cannot be caught until an attempt is made to run the code. That's just how Python works.
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
answered Jun 13, 2012 at 1:16
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
Comments
lang-py
""" """if you want the string to span over multiple lines.