Python脚本遇traceback错误后如何继续执行?
解决Python邮件脚本报错后终止运行的问题
问题描述
运行邮件发送脚本时,偶尔会触发如下错误,导致脚本直接停止:
Traceback (most recent call last): File "main.py", line 45, in <module> server.sendmail(sender, receiver, msg.as_string()) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/smtplib.py", line 899, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'example@gmail.com': (550, b'The mail server could not deliver mail to example@gmail.com. The account\nor domain may not exist, they may be blacklisted, or missing the proper dns\nentries.')}
当前使用的代码片段:
with smtplib.SMTP(smtpsv, port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, receiver, msg.as_string()) print(" + {}: {} sent successfully".format(count, line.strip()))
需要实现:脚本遇到任何错误后不终止,继续执行后续任务。
解决方案
使用Python的try-except异常捕获机制,将可能抛出错误的代码包裹在try块中,异常发生时进入except块处理,避免脚本终止。
修改后的代码示例:
import smtplib with smtplib.SMTP(smtpsv, port) as server: server.starttls() # 建立加密连接 server.login(user, password) try: # 尝试发送邮件 server.sendmail(sender, receiver, msg.as_string()) print(f" + {count}: {line.strip()} 发送成功") except smtplib.SMTPRecipientsRefused as e: # 单独处理收件人拒绝的异常 print(f" - {count}: {line.strip()} 发送失败:收件人被拒绝,错误信息: {str(e)}") except Exception as e: # 捕获其他所有异常,确保脚本继续运行 print(f" - {count}: {line.strip()} 发送失败:未知错误,错误信息: {str(e)}")
关键说明
- 优先捕获特定异常(比如
SMTPRecipientsRefused),可以更精准地处理不同类型的错误 - 最后用
Exception兜底,覆盖其他未预见的异常,避免脚本终止 - 在
except块中打印错误详情,方便后续排查问题 - 如果是批量发送邮件的场景,这个逻辑能保证某一封邮件发送失败时,不影响后续邮件的发送
内容的提问来源于stack exchange,提问作者Sane Chamak Mak
相关产品推荐
相关产品推荐

