[英]python: how to get line text where exception occur, not line number
I am trying to use sys.excepthook我正在尝试使用sys.excepthook
With below hook带下钩
def foo(type, value, traceback):
# how to print the line that except occurs
sys.excepthook = foo
and use like below并使用如下
$ python3
>>> text that cause error
How to define foo
such that text that cause error
being printed?如何定义foo
以便打印text that cause error
?
EDIT编辑
Let me add the full story, to make it clear.让我添加完整的故事,以使其清楚。 (deserve downvotes? -) ) (应该投反对票?-))
What I want is not print the line, is我想要的不是打印行,是
eg, if type例如,如果输入
>>> import requests
>>> edit requests
get the line that exception occurs, ie, edit requests
获取发生异常的行,即edit requests
then exec edit(find_file(request))
然后执行edit(find_file(request))
where edit()
use subprocess.call()
, find_file
use inspect
to find the file where an object being defined.其中edit()
使用subprocess.call()
, find_file
使用inspect
查找定义对象的文件。
Yes, I know ipython magics, and use it regularlly.是的,我知道 ipython 魔法,并且经常使用它。 this time I am ask to how to define it.这次我问如何定义它。
You can use the modul traceback and the passed traceback
object's tb_lineno
attribute:您可以使用模块回溯和传递的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")
Out:出去:
The line where the exception occurs: int("text")
as the the line int("text")
line raised an exeption.因为int("text")
行引发了一个例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.