[英]Is there any way to capture exact line number where exception happened in python
Hi is there any way to get the exact line number where the exception happen?嗨,有什么方法可以获取发生异常的确切行号? because i am using a wrapper method and in actual method there are many lines of code and i am getting a very generic exception and not sure where exactly it is happening.因为我使用的是包装器方法,而在实际方法中,有很多行代码,我得到了一个非常通用的异常,并且不确定它到底发生在哪里。 Eg code as below,例如如下代码,
import sys
def test(**kwargs):
print (kwargs)
abc
def wraper_test(**kwargs):
try:
test(**kwargs)
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
print(exception_object.tfline_no)
wraper_test(hello="test", value="lsdf")
Now in the exception line number what i am getting is for test(**kwargs) and not the exact location where the exception is generated in this case "abc" which is inside the test method.现在在异常行号中,我得到的是 test(**kwargs) 而不是在这种情况下生成异常的确切位置“abc”,它位于测试方法内部。
Is there any way to capture the exact line number in exception when we are using wrapper method?当我们使用包装器方法时,有什么方法可以捕获异常中的确切行号?
Try this: the traceback library allows you to get a longer stack trace with more line numbers (this shows the real error is on line 5).试试这个:回溯库允许您获得更长的堆栈跟踪和更多的行号(这表明真正的错误在第 5 行)。
import sys, traceback
def test(**kwargs):
print (kwargs)
abc
def wrapper_test(**kwargs):
try:
test(**kwargs)
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
traceback.print_tb(exception_traceback, limit=2, file=sys.stdout)
wrapper_test(hello="test", value="lsdf")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.