简体   繁体   English

Python traceback.print_exc()返回'None'

[英]Python traceback.print_exc() returns 'None'

This function is supposed to catch exceptions in the main execution. 该函数应该捕获主执行中的异常。 If there is an exception it should print out the error with log.error(traceback.print_exc()) and clean up with exit_main() . 如果有一个例外,它应该打印出误差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()

Unfortunately log.error(traceback.print_exc()) does only return None if there is an exception. 遗憾的是,如果存在异常, log.error(traceback.print_exc())仅返回None How can I make traceback print the full error report in this case? 在这种情况下,如何使回溯打印完整的错误报告?

PS: I use python 3.4. PS:我使用python 3.4。

From its __doc__ : 从它的__doc__

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

That is, it isn't supposed to return anything, its job is to print. 也就是说,它不应该返回任何东西,它的工作是打印。 If you want the traceback as a string to be logged, use traceback.format_exc() instead. 如果要将跟踪作为字符串记录,请改用traceback.format_exc()

I usually use traceback.print_exc() just for debugging. 我通常只使用traceback.print_exc()进行调试。 In your case, to log your exception you can simply do the following: 在您的情况下,要记录您的异常,您只需执行以下操作:

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

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

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