[英]How to print traceback message to new line in 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 打印(100/0)ZeroDivisionError:除以零
預期輸出應該是新行中的每條消息:
異常數據:回溯(最近一次調用):
文件“C:\\Build\\test\\workfile\\python-practice\\exception_test.py”,第 54 行,
在 get_details 打印(100/0)
ZeroDivisionError:整數除法或模數為零
為了更好和漂亮地打印異常,請參閱Python 的 Traceback 庫
具體來說,檢查 format_* 方法(例如 format_exception())
在 HTML 中,您可以使用換行符<br>
將異常放在另一行。 此外,您可以稍微更改格式。 由於格式化程序中只有一個參數,因此您可以只使用位置參數而不是關鍵字參數。
html = """
<html>
<body>
<b> Exception Data: </b>
<br>
{}
</body>
</html>
""".format(exp_message)
只需用 HTML 的換行符替換 Python 的換行符即可。
html_exp_message = exp_message.replace('\n', '<br>')
html = """
<html>
<body>
<b> Exception Details: </b> {}
</body>
</html>
""".format(html_exp_message)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.