首页 > 解决方案 > 如何在python中将回溯消息打印到新行

问题描述

我正在使用 html 电子邮件和 .format() 作为字符串传递参数

下面是我的python代码:

import sys

try:
    print(5 / 0)
except Exception as e:
    send_error_email(exp_message=format_exc())

然后获取函数 send_error_email 并传递给 MIMEMultipart 邮件脚本

 html = """
            <html>
              <body>
    
                <b> Exception Details: </b> {exp_message}
    
              </body>
            </html>
            """.format(exp_message=exp_message)

在邮件中的一行中获取输出

异常数据:回溯(最近一次调用最后一次):文件“C:\Build\test\workfile\python-practice\exception_test.py”,第 54 行,在 get_details print(100/0) ZeroDivisionError:除以零

预期输出应该是新行中的每条消息

异常数据:回溯(最近一次调用):
文件“C:\Build\test\workfile\python-practice\exception_test.py”,第 54 行,
在 get_details print(100/0)
ZeroDivisionError:整数除法或模除以零

标签: python

解决方案


为了更好和漂亮地打印异常,请具体参考Python 的 Traceback 库
,检查 traceback.format_* 方法(例如 format_exception())


推荐阅读