Python traceback.print_exc()返回'None'

时间:2016-10-25 12:38:18

标签: python exception-handling traceback

该函数应该捕获主执行中的异常。如果有异常,则应使用log.error(traceback.print_exc())打印出错误并使用exit_main()进行清理。

def main():
    try:
        exec_app()
    except KeyboardInterrupt:
        log.error('Error: Backup aborted by user.')
        exit_main()
    except Exception:
        log.error('Error: An Exception was thrown.')
        log.error("-" * 60)
        log.error(traceback.print_exc())
        log.error("-" * 60)
        exit_main()

如果存在异常,log.error(traceback.print_exc())只会返回None。在这种情况下,如何使回溯打印完整的错误报告?

PS:我使用python 3.4。

2 个答案:

答案 0 :(得分:7)

来自__doc__

Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'

也就是说,它不应该返回任何东西,它的工作是打印。如果要将回溯记录为字符串,请改用traceback.format_exc()

答案 1 :(得分:1)

我通常只使用traceback.print_exc()进行调试。在您的情况下,要记录您的例外,您只需执行以下操作:

try:
    # Your code that might raise exceptions
except SomeSpecificException as e:
    # Do something (log the exception, rollback, etc)
except Exception as e:
    log.error(e)  # or log(e.message) if you want to log only the message and not all the error stack