簡體   English   中英

python:如何獲取發生異常的行文本,而不是行號

[英]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")行引發了一個例外。

我們可以使用traceback模塊來幫助我們。

def foo(type, value, trace):
    print(trace.msg)

回溯對象將包含大量有關錯誤發生位置的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM