如何处理python脚本错误并通过电子邮件发送

如何处理python脚本错误并通过电子邮件发送,python,python-3.x,Python,Python 3.x,我对Python比较陌生 我有一个Python脚本,它从互联网上获取一些信息,然后插入数据库。我想每天用cron运行它,并让脚本在完成后每天给我发送一封电子邮件 我已经计算出了电子邮件部分,它正在发送经过的时间和插入数据库的总记录,如下所示: 在脚本的开头: records_inserted = 0 t1_start = time.perf_counter() t1_stop = time.perf_counter() msg = EmailMessage() msg.set_conten

我对Python比较陌生

我有一个Python脚本,它从互联网上获取一些信息,然后插入数据库。我想每天用cron运行它,并让脚本在完成后每天给我发送一封电子邮件

我已经计算出了电子邮件部分,它正在发送经过的时间和插入数据库的总记录,如下所示:

在脚本的开头:

records_inserted = 0
t1_start = time.perf_counter()
t1_stop = time.perf_counter()

msg = EmailMessage()

msg.set_content("Total elapsed time: %.1f [min]" % ((t1_stop-t1_start)/60) + 
"\n\nThe total number of records inserted in the database was: " + 
str(records_inserted))

email_from = “xxxxxxx@gmail.com"
email_to = “xxxxx@xxxx.com"
gmail_password = “xxxxxx”

msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = “Script executed"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_from, gmail_password)
server.send_message(msg)

server.quit()
在脚本的末尾:

records_inserted = 0
t1_start = time.perf_counter()
t1_stop = time.perf_counter()

msg = EmailMessage()

msg.set_content("Total elapsed time: %.1f [min]" % ((t1_stop-t1_start)/60) + 
"\n\nThe total number of records inserted in the database was: " + 
str(records_inserted))

email_from = “xxxxxxx@gmail.com"
email_to = “xxxxx@xxxx.com"
gmail_password = “xxxxxx”

msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = “Script executed"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_from, gmail_password)
server.send_message(msg)

server.quit()
现在,如果网页中的某些内容是我从中断或更改中获取的,或者由于任何原因存在任何错误,我希望在每日电子邮件中也能看到这些错误

如果在执行过程中出现一个或多个错误,处理和存储(可能是数组)的最佳方法是什么,并将错误号和描述作为电子邮件正文的一部分写入电子邮件,以便我尽快知道,并在必要时查看和更正


谢谢

评论中@fernandezcuesta提出的解决方案对我来说很有效


我将所有“完成任务”的代码打包成一个
try:Exception as _ex:
并将
repr(_ex)
附加到我的邮件中

您已经在使用数据库了,因此,您可以将错误记录到数据库中,并在您的电子邮件功能中检索它们。谢谢@MikeScotty,但我想知道的是任何潜在的Python错误,并在日常电子邮件中看到它们,如果有任何错误,您只需将所有“完成任务”的代码包装成一个
try:
,例外情况除外,例如:
,然后附加
repr(_ex)
发送至您的邮件谢谢@fernandezcuesta这完全符合我的需要,错误包含在电子邮件正文中,但不再显示在我编写脚本时运行脚本的终端窗口中,不确定原因。继续在终端窗口中显示错误并将其包含在电子邮件中的任何方法(此操作已在运行)。谢谢“只是
打印(repr(_ex))
或使用