[英]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.