简体   繁体   English

有什么方法可以捕获 python 中发生异常的确切行号

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

相关问题 python:如何获取发生异常的行文本,而不是行号 - python: how to get line text where exception occur, not line number 如何获取发生python异常的实际行号? - How to get actual line number of where python exception occurred? 定位python代码中发生异常的行号 - Locating the line number where an exception occurs in python code 有没有办法用 python 捕获 selenium 请求标头? - Is there any way to capture selenium request headers with python? Python中Line的异常数 - Line's number of Exception in Python Python 异常处理-行号 - Python exception handling - line number 有什么方法可以识别 PDF 是否被编辑/篡改,以及 PDF 使用 Python 编辑/篡改的确切位置? - Is there any way that I can identify whether the PDF is edited/tampered and the exact location where the PDF is edited/tampered using Python? 捕获文件和行号以获取未引发的异常 - Capture file and line number for an exception that wasn't raised 在python中找到大数阶乘的确切值的最快方法是什么? - What is the fastest way to find the exact value of the factorial of a large number in python? Python Google App Engine 项目中发生内存泄漏。 任何有效的方法来编写我的操作? - Memory leak happened in Python Google App Engine project. Any efficient way to write my operation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM