import sys
import linecache
# copied from somewhere
def PrintException():
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
def m1():
# some code
try:
try:
m1()
except:
PrintException()
except:
PrintException()
它写了Exception行的m1()
- 被称为行的数量,但我需要在函数m1
中准确地知道异常行的数字。你能说出怎么知道吗?
答案 0 :(得分:0)
要获取异常,您必须遍历.tb_next
import requests, re, time, json, urllib2
import math, os, time
from datetime import datetime
import sys
import linecache
# copied from somewhere
def PrintException():
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
if tb.tb_next:
tb_next = tb.tb_next
while tb_next: # loop until the value is 'None'
lineno = tb_next.tb_lineno
tb_next = tb_next.tb_next
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
def m1():
# some code
raise ValueError('Value error')
try:
try:
m1()
except:
PrintException()
except:
PrintException()
它将输出line 25
而不是29
或不与m1()
的行
EXCEPTION IN (main.py, LINE 25 "raise ValueError('Value error')"): Value error