【问题标题】:How to print traceback message to new line in python [duplicate]如何在python中将回溯消息打印到新行[重复]
【发布时间】:2021-10-20 07:21:16
【问题描述】:

我正在使用 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 打印(100/0)
ZeroDivisionError:整数除法或除以零

【问题讨论】:

  • @enzo 你的意思是 send_error_email(exp_message='
    '.join(format_exc().splitlines()))

标签: python


【解决方案1】:

要更好、更漂亮地打印异常,请参阅Python's Traceback Library
具体来说,检查 traceback.format_* 方法(例如 format_exception())

【讨论】:

    【解决方案2】:

    在 HTML 中,您可以使用换行符 &lt;br&gt; 将异常放在另一行。此外,您可以稍微更改格式。由于格式化程序中只有一个参数,您可以只使用位置参数而不是关键字参数。

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

    【讨论】:

    • 我试过仍然所有的 trackeback messege 只打印在一行中,我需要将每个数据都换成新行
    【解决方案3】:

    只需将 Python 的换行符替换为 HTML 的换行符即可。

    html_exp_message = exp_message.replace('\n', '<br>')
    
    html = """
                <html>
                  <body>
                    <b> Exception Details: </b> {}
                  </body>
                </html>
                """.format(html_exp_message)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多