繁体   English   中英

Python中Line的异常数

[英]Line's number of Exception in Python

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()

它写了m1()的Exception行号,即行,但是我需要在函数m1确切地知道Exception行号。 你能说出如何知道吗?

要获取异常,您必须遍历.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

暂无
暂无

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

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