簡體   English   中英

Python 在腳本遇到異常時發送郵件

[英]Python sending mail when script gets an exception

我想知道以下是否是完成我想要的好方法。

我有一個名為main.py的腳本,假設它無限期地運行並且對某些異常進行異常處理。 現在我想要的是在發生任何未處理的新異常時向我發送 email。 還有比這更好的方法嗎? 這是一個新文件main_wrapper.py

try:
    import main # this will start the function in main, no `if __name__` condition is present here
except Exception as e:
    send_mail(e) # send_mail is a function that will send me an email

有沒有更好的方法來處理這個問題?

PS:我不是問如何寫send_mail function。 我只想知道try...except處理這個問題的方法是好是壞。

謝謝,格魯吉亞

這是處理此問題的最佳方法,使用try except塊。

我建議你改變:

except Exception as e:

except BaseException as e:

BaseException 是 python 中所有異常的根源。

(如果您想捕獲所有異常)

如果您想做更復雜的事情,只需詢問即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM