相关疑难解决方法(0)

Python当我捕获异常时,如何获取类型,文件和行号?

捕获将如此打印的异常:

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)

python exception-handling exception stack-trace

231
推荐指数
6
解决办法
19万
查看次数

如何从Python中的exec或execfile获取错误的行号

假设我有以下多行字符串:

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)

python python-2.7

10
推荐指数
1
解决办法
4321
查看次数