1

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.

2
  • use triple quotes """ """ if you want the string to span over multiple lines. Commented Jun 13, 2012 at 1:06
  • The answer below looks fine. For future reference, an api that takes a file will also work with a 'file-like object', see the StringIO module which can be used to make a string that can be read as if it were a file. Commented Jun 13, 2012 at 1:12

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hmm, yeah, but I was hoping to stay away from file IO
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?
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
"division by zero" cannot be caught until an attempt is made to run the code. That's just how Python works.
1
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.