Python中的异常行数

2024-09-30 06:15:32 发布

您现在位置: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()调用行的编号,但是我需要在函数m1中准确地知道异常行的编号。你能告诉我怎么知道吗?你知道吗


Tags: importobjdefsyslinecodefilenametb
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:32

要获取异常,必须循环.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 25not 29或不带m1()的行

EXCEPTION IN (main.py, LINE 25 "raise ValueError('Value error')"): Value error

相关问题 更多 >

    热门问题