Let's say I have the following multi-line string:
cmd = """
a = 1 + 1
b = [
2 + 2,
4 + 4,
]
bork bork bork
"""
and I want to execute it in a particular scope:
scope = {}
exec( cmd, scope )
print scope[ 'b' ]
There's a SyntaxError
at line 6 of the command, and I want to be able to report that to the user. How do I get the line number? I've tried this:
try:
exec( cmd, scope ) # <-- let's say this is on line 123 of the source file
except Exception, err:
a, b, c = sys.exc_info()
line_number = c.tb_lineno # <-- this gets me 123, not 6
print "%s at line %d (%s)" % ( a, line_number, b.message )
...but I get the line number of the exec
statement, not the line number within the multi-line command.
Update: it turns out the handling of the type of exception that I arbitrarily chose for this example, the SyntaxError
, is different from the handling of any other type. To clarify, I'm looking a solution that copes with any kind of exception.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…