捕获将如此打印的异常:
Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
我想将其格式化为:
ZeroDivisonError, tmp.py, 1
Run Code Online (Sandbox Code Playgroud) 假设我有以下多行字符串:
cmd = """
a = 1 + 1
b = [
2 + 2,
4 + 4,
]
bork bork bork
"""
Run Code Online (Sandbox Code Playgroud)
我想在特定范围内执行它:
scope = {}
exec( cmd, scope )
print scope[ 'b' ]
Run Code Online (Sandbox Code Playgroud)
有一个SyntaxError在命令的第6行,我希望能够向大家报告,给用户.我如何获得行号?我试过这个:
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 …Run Code Online (Sandbox Code Playgroud)