[英]Is there any way to capture exact line number where exception happened in python
嗨,有什么方法可以獲取發生異常的確切行號? 因為我使用的是包裝器方法,而在實際方法中,有很多行代碼,我得到了一個非常通用的異常,並且不確定它到底發生在哪里。 例如如下代碼,
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")
現在在異常行號中,我得到的是 test(**kwargs) 而不是在這種情況下生成異常的確切位置“abc”,它位於測試方法內部。
當我們使用包裝器方法時,有什么方法可以捕獲異常中的確切行號?
試試這個:回溯庫允許您獲得更長的堆棧跟蹤和更多的行號(這表明真正的錯誤在第 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.