繁体   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