简体   繁体   English

python:如何获取发生异常的行文本,而不是行号

[英]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我想要的不是打印行,是

  • get the line得到线
  • if the line match some criterion, modify then exec如果该行匹配某个条件,则修改然后执行

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")行引发了一个例外。

We can use the traceback module to help us.我们可以使用traceback模块来帮助我们。

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

The traceback object will have lots of information about where the error occurred.回溯对象将包含大量有关错误发生位置的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM