How to save traceback / sys.exc_info() values in a variable?

前端 未结 5 1316
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 05:33

I want to save the name of the error and the traceback details into a variable. Here\'s is my attempt.

import sys
try:
    try:
        print x
    except E         


        
5条回答
  •  盖世英雄少女心
    2020-12-02 06:26

    Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

    Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

    Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

    Remember to import traceback.

    Here's the output from traceback.extract_stack(). Formatting added for readability.

    >>> traceback.extract_stack()
    [
       ('', 1, '', None),
       ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
       ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
       ('', 1, '', None)
    ]
    

    Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

    >>> ''.join(traceback.format_stack())
    '  File "", line 1, in \n
       File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
           ret = method(*args, **kwargs)\n
       File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
           exec(code, self.locals)\n  File "", line 1, in \n'
    

提交回复
热议问题