代码之家  ›  专栏  ›  技术社区  ›  chriscauley

如何在不停止程序的情况下打印完整的回溯?

  •  587
  • chriscauley  · 技术社区  · 16 年前

    我想在不退出的情况下捕获并记录异常,例如。,

    try:
        do_stuff()
    except Exception, err:
        print(Exception, err)
        # I want to print the entire traceback here,
        # not just the exception name and details
    

    我想打印与在没有try的情况下引发异常时打印的输出完全相同的输出..除了拦截异常,我确实这样做了 不 希望它退出我的程序。我该怎么做?

    10 回复  |  直到 6 年前
        1
  •  695
  •   Mr_and_Mrs_D    11 年前

    其他一些答案已经指出了问题的症结所在 traceback 模块。

    请注意这一点 print_exc ,在某些情况下,你不会得到你所期望的。在Python 2.x中:

    import traceback
    
    try:
        raise TypeError("Oups!")
    except Exception, err:
        try:
            raise TypeError("Again !?!")
        except:
            pass
    
        traceback.print_exc()
    

    …将显示 最后的

    Traceback (most recent call last):
      File "e.py", line 7, in <module>
        raise TypeError("Again !?!")
    TypeError: Again !?!
    

    如果你真的需要访问原件 回溯 异常信息 作为从 exc_info 并使用 print_exception :

    import traceback
    import sys
    
    try:
        raise TypeError("Oups!")
    except Exception, err:
        try:
            exc_info = sys.exc_info()
    
            # do you usefull stuff here
            # (potentially raising an exception)
            try:
                raise TypeError("Again !?!")
            except:
                pass
            # end of useful stuff
    
    
        finally:
            # Display the *original* exception
            traceback.print_exception(*exc_info)
            del exc_info
    

    Traceback (most recent call last):
      File "t.py", line 6, in <module>
        raise TypeError("Oups!")
    TypeError: Oups!
    

    不过,这方面的陷阱很少:

    • sys_info :

      将回溯返回值赋给处理异常的函数中的局部变量将导致 . 这将防止被同一函数中的局部变量或回溯引用的任何内容被垃圾收集。[...] 如果确实需要回溯,请确保在使用后将其删除

    • 从Python2.2开始,这样的循环会自动回收


    另一方面,通过允许您访问回溯 作为一个例外,python3产生了一个不那么令人惊讶的结果:

    import traceback
    
    try:
        raise TypeError("Oups!")
    except Exception as err:
        try:
            raise TypeError("Again !?!")
        except:
            pass
    
        traceback.print_tb(err.__traceback__)
    

    ... 将显示:

      File "e3.py", line 4, in <module>
        raise TypeError("Oups!")
    
        2
  •  782
  •   taras Hardik Kamdar    7 年前

    traceback.format_exc() 或 sys.exc_info() 如果你想要的话,我会提供更多的信息。

    import traceback
    import sys
    
    try:
        do_stuff()
    except Exception:
        print(traceback.format_exc())
        # or
        print(sys.exc_info()[2])
    
        3
  •  294
  •   dimo414    11 年前

    如果您正在调试并且只想查看当前堆栈跟踪,则只需调用:

    traceback.print_stack()

        4
  •  140
  •   Aaron Hall    6 年前

    try:
        do_something_that_might_error()
    except Exception as error:
        handle_the_error(error)
    

    为了提取完整的回溯,我们将使用 traceback 标准库中的模块:

    import traceback
    

    def raise_error():
        raise RuntimeError('something bad happened!')
    
    def do_something_that_might_error():
        raise_error()
    

    印刷

    至 打印 完全回溯,使用 traceback.print_exc 方法:

    try:
        do_something_that_might_error()
    except Exception as error:
        traceback.print_exc()
    

    打印内容:

    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "<stdin>", line 2, in do_something_that_might_error
      File "<stdin>", line 2, in raise_error
    RuntimeError: something bad happened!
    

    不过,最好的做法是为您的模块设置一个记录器。它将知道模块的名称,并能够更改级别(以及其他属性,例如处理程序)

    import logging
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    

    在这种情况下,你会想要 logger.exception 改为函数:

    try:
        do_something_that_might_error()
    except Exception as error:
        logger.exception(error)
    

    哪些日志:

    ERROR:__main__:something bad happened!
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "<stdin>", line 2, in do_something_that_might_error
      File "<stdin>", line 2, in raise_error
    RuntimeError: something bad happened!
    

    或者你只是想要字符串,在这种情况下,你会想要 traceback.format_exc 改为函数:

    try:
        do_something_that_might_error()
    except Exception as error:
        logger.debug(traceback.format_exc())
    

    DEBUG:__main__:Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "<stdin>", line 2, in do_something_that_might_error
      File "<stdin>", line 2, in raise_error
    RuntimeError: something bad happened!
    

    结论

    对于这三个选项,我们看到的输出与出错时相同:

    >>> do_something_that_might_error()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in do_something_that_might_error
      File "<stdin>", line 2, in raise_error
    RuntimeError: something bad happened!
    

    性能问题在这里并不重要,因为IO通常占主导地位。我更喜欢,因为它以向前兼容的方式精确地执行请求:

    logger.exception(error)
    

        5
  •  24
  •   TZubiri    7 年前

    首先,不要使用 print 对于测井,有一个稳定的、经过验证的、经过深思熟虑的标准lib模块可以做到这一点: logging . 你肯定 改用它。

    混乱 当有本地和简单的方法时,使用不相关的工具。在这里:

    log = logging.getLogger(__name__)
    
    try:
        call_code_that_fails()
    except MyError:
        log.exception('Any extra info you want to see in your logs')
    

    向任何对引擎盖下的工作方式感兴趣的人解释

    什么 log.exception log.error (即,以级别记录事件 ERROR ) 然后打印回溯。

    好吧,这里有一些考虑:

    • 正确的
    • 这很简单。

    为什么没人用 traceback 或呼叫记录器 exc_info=True 或者把他们的手弄脏 sys.exc_info ?

    好吧,就因为!它们都是为了不同的目的而存在的。例如, traceback.print_exc 的输出与解释器本身产生的回溯略有不同。如果你用它,你会把任何读你日志的人弄糊涂,他们会把头撞在上面。

    经过 exc\ U info=真 记录电话是不合适的。 INFO log.exception异常 只生成一个级别的日志- .

    你绝对应该避免和 系统exc\U信息 尽你所能。它不是一个公共接口,而是一个内部接口-你

        6
  •  15
  •   Neuron MonoThreaded    5 年前

    除了 Aaron Hall's answer ,如果您正在登录,但不想使用 logging.exception() (因为它是在错误级别记录的),所以可以使用较低的级别并传递 exc_info=True . 例如

    try:
        do_something_that_might_error()
    except Exception:
        logging.info('General exception noted.', exc_info=True)
    
        7
  •  14
  •   bgdnlp    7 年前

    其他答案中我没有提到这一点。如果出于任何原因传递异常对象。。。

    在python3.5+中,可以使用 traceback.TracebackException.from_exception() . 例如:

    import traceback
    
    
    def stack_lvl_3():
        raise Exception('a1', 'b2', 'c3')
    
    
    def stack_lvl_2():
        try:
            stack_lvl_3()
        except Exception as e:
            # raise
            return e
    
    
    def stack_lvl_1():
        e = stack_lvl_2()
        return e
    
    e = stack_lvl_1()
    
    tb1 = traceback.TracebackException.from_exception(e)
    print(''.join(tb1.format()))
    

    Traceback (most recent call last):
      File "exc.py", line 10, in stack_lvl_2
        stack_lvl_3()
      File "exc.py", line 5, in stack_lvl_3
        raise Exception('a1', 'b2', 'c3')
    Exception: ('a1', 'b2', 'c3')
    

    这仅仅是堆栈的两个级别,而不是在异常被引发的情况下在屏幕上打印的内容 stack_lvl_2() 未被拦截(取消对 # raise 行)。

    据我所知,这是因为异常在引发时只记录堆栈的当前级别, stack_lvl_3() 在这种情况下。当它通过堆栈向上传递时,更多的级别被添加到它的 __traceback__ . 但我们在里面截获了 意味着它只记录了3级和2级。要得到打印在标准输出上的完整跟踪,我们必须在最高点(最低点?)级别:

    import traceback
    
    
    def stack_lvl_3():
        raise Exception('a1', 'b2', 'c3')
    
    
    def stack_lvl_2():
        stack_lvl_3()
    
    
    def stack_lvl_1():
        stack_lvl_2()
    
    
    try:
        stack_lvl_1()
    except Exception as exc:
        tb = traceback.TracebackException.from_exception(exc)
    
    print('Handled at stack lvl 0')
    print(''.join(tb.stack.format()))
    

    结果是:

    Handled at stack lvl 0
      File "exc.py", line 17, in <module>
        stack_lvl_1()
      File "exc.py", line 13, in stack_lvl_1
        stack_lvl_2()
      File "exc.py", line 9, in stack_lvl_2
        stack_lvl_3()
      File "exc.py", line 5, in stack_lvl_3
        raise Exception('a1', 'b2', 'c3')
    

    different format() .

    在尽可能远离引发异常的点处截取异常,可以简化代码,同时提供更多信息。

        8
  •  8
  •   Edward Newell Kuldeep    11 年前

    为了得到 精确的 堆栈跟踪,作为一个字符串 如果没有try/except跳过它,只需将它放在捕获违规异常的except块中。

    desired_trace = traceback.format_exc(sys.exc_info())
    

    下面是如何使用它(假设 flaky_func 定义,以及 log

    import traceback
    import sys
    
    try:
        flaky_func()
    except KeyboardInterrupt:
        raise
    except Exception:
        desired_trace = traceback.format_exc(sys.exc_info())
        log(desired_trace)
    

    抓住并重新饲养是个好主意 KeyboardInterrupt s、 因此,您仍然可以使用Ctrl-C终止程序。日志记录不在问题的范围之内,但是一个好的选择是 logging sys 和 traceback

        9
  •  7
  •   Ivo van der Wijk    16 年前

    for i in something:
        for j in somethingelse:
            for k in whatever:
                try:
                    something_complex(i, j, k)
                except Exception, e:
                    print e
            try:
                something_less_complex(i, j)
            except Exception, e:
                print e
    

    换句话说,您需要将try/except中可能失败的语句尽可能具体地包装在最内部的循环中。

        10
  •  7
  •   Basj    8 年前

    关于…的评论 this answer 的评论: print(traceback.format_exc()) 对我来说比 traceback.print_exc() hello

    回溯(最近一次呼叫):
    文件“C:\Users\User\Desktop\测试.py,第7行,在
    做些事情()
    文件“C:\Users\User\Desktop\测试.py“,第4行,在do\u stuff中”
    1/0
    ZeroDivisionError:整数被零除或模被零除
    o

    import traceback, sys
    
    def do_stuff():
        1/0
    
    try:
        do_stuff()
    except Exception:
        print(traceback.format_exc())
        print('hello')
    
        11
  •  6
  •   Ciro Santilli OurBigBook.com    6 年前

    traceback.format_exception

    如果只有exception对象,则可以使用以下命令从Python 3中的任意代码点以字符串形式获取回溯:

    import traceback
    
    ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
    

    完整示例:

    #!/usr/bin/env python3
    
    import traceback
    
    def f():
        g()
    
    def g():
        raise Exception('asdf')
    
    try:
        g()
    except Exception as e:
        exc = e
    
    tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
    print(tb_str)
    

    输出:

    Traceback (most recent call last):
      File "./main.py", line 12, in <module>
        g()
      File "./main.py", line 9, in g
        raise Exception('asdf')
    Exception: asdf
    

    https://docs.python.org/3.7/library/traceback.html#traceback.format_exception

    Extract traceback info from an exception object

    在python3.7.3中测试。

        12
  •  4
  •   Nycki    7 年前

    如果您已经有一个错误对象,并且您想要打印整个内容,那么您需要进行这个稍微尴尬的调用:

    import traceback
    traceback.print_exception(type(err), err, err.__traceback__)
    

    这是正确的, print_exception 拿 三 位置参数:异常的类型、实际的异常对象和异常自身的内部回溯属性。

    在Python3.5或更高版本中 type(err) 是可选的。。。但这是一个位置参数,所以您仍然必须在其位置显式传递None。

    traceback.print_exception(None, err, err.__traceback__)
    

    traceback.print_exception(err) . 我无法理解为什么你会想要打印出一个错误,以及一个不是属于那个错误的回溯。

        13
  •  3
  •   nmichaels    16 年前

    traceback 模块。它将允许您像Python通常那样打印堆栈转储。特别是 print_last 函数将打印最后一个异常和堆栈跟踪。

        14
  •  0
  •   Ahmad    6 年前

    import logging, sys
    import traceback
    logging.basicConfig(filename='error.log', level=logging.DEBUG)
    
    def handle_exception(exc_type, exc_value, exc_traceback):
        import sys
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        exc_info=(exc_type, exc_value, exc_traceback)
        logging.critical("\nDate:" + str(datetime.datetime.now()), exc_info=(exc_type, exc_value, exc_traceback))
        print("An error occured, check error.log to see the error details")
        traceback.print_exception(*exc_info)
    
    
    sys.excepthook = handle_exception
    
        15
  •  0
  •   A.I.    5 年前

    你可以做:

    try:
        do_stuff()
    except Exception, err:
        print(Exception, err)
        raise err
    
        16
  •  0
  •   Neuron MonoThreaded    5 年前

    python 3解决方案

    stacktrace_helper.py

    from linecache import getline
    import sys
    import traceback
    
    
    def get_stack_trace():
        exc_type, exc_value, exc_tb = sys.exc_info()
        trace = traceback.format_stack()
        trace = list(filter(lambda x: ("\\lib\\" not in x and "/lib/" not in x and "stacktrace_helper.py" not in x), trace))
        ex_type = exc_type.__name__
        ex_line = exc_tb.tb_lineno
        ex_file = exc_tb.tb_frame.f_code.co_filename
        ex_message = str(exc_value)
        line_code = ""
        try:
            line_code = getline(ex_file, ex_line).strip()
        except:
            pass
    
        trace.insert(
            0, f'File "{ex_file}", line {ex_line}, line_code: {line_code} , ex: {ex_type} {ex_message}',
        )
        return trace
    
    
    def get_stack_trace_str(msg: str = ""):
        trace = list(get_stack_trace())
        trace_str = "\n".join(list(map(str, trace)))
        trace_str = msg + "\n" + trace_str
        return trace_str