[英]python: how to get line text where exception occur, not line number
我正在尝试使用sys.excepthook
带下钩
def foo(type, value, traceback):
# how to print the line that except occurs
sys.excepthook = foo
并使用如下
$ python3
>>> text that cause error
如何定义foo
以便打印text that cause error
?
编辑
让我添加完整的故事,以使其清楚。 (应该投反对票?-))
我想要的不是打印行,是
例如,如果输入
>>> import requests
>>> edit requests
获取发生异常的行,即edit requests
然后执行edit(find_file(request))
其中edit()
使用subprocess.call()
, find_file
使用inspect
查找定义对象的文件。
是的,我知道 ipython 魔法,并且经常使用它。 这次我问如何定义它。
您可以使用模块回溯和传递的traceback
对象的tb_lineno
属性:
import sys
import traceback as tb
def foo(type, value, traceback):
# how to print the line that except occurs
print("The line where the exception occurs: {}".format(tb.linecache.getline(tb.extract_tb(sys.last_traceback)[0].filename, traceback.tb_lineno)))
sys.excepthook = foo
int("text")
出去:
The line where the exception occurs: int("text")
因为int("text")
行引发了一个例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.