0

我已经设置了一个 python 脚本来在表中插入一条新记录,发送一封电子邮件并在成功发送电子邮件后更新最近插入的记录。Python脚本如下:

import smtplib
import pyodbc
import time
import os
import time
from smtplib import SMTPException
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
localtime = time.asctime( time.localtime(time.time()) )
fromAddress = "sender@mydomain.com"
toAddress = "myEmail@mydomain.com"
email = MIMEMultipart()
email['From'] = fromAddress
email['To'] = toAddress
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=mySQLServer;DATABASE=mydb;UID=username;PWD=password')
cursor = connection.cursor()
query = "INSERT INTO [mydb].[dbo].[Logger] ([ScriptStartTime], [EmailSent?]) VALUES (CURRENT_TIMESTAMP, 0);"
cursor.execute(query)
print "************************Python Script Log Started at", localtime,"**********************"
def update():
   updateEmailFlagQuery = ("UPDATE [mydb].[dbo].[Logger] SET [EmailSent?] = 1, [EmailSentTime] = CURRENT_TIMESTAMP WHERE ID = (SELECT MAX(ID) FROM [mydb].[dbo].[Logger])")
   updateEmailFlag = cursor.execute(updateEmailFlagQuery)
   connection.commit()
def notify(email, body, fromAddress, toAddress):
   email['Subject'] = "It Worked"
   email.attach(MIMEText(body, 'plain'))
   server = smtplib.SMTP('SMTPServer', 25)
   server.set_debuglevel(True)
   text = email.as_string()
   server.sendmail(fromAddress, toAddress, text)
   server.quit()
   connection.commit()
try:
   body = "This is an Email sent from Scheduled Python Script"
   notify(email, body, fromAddress, toAddress)
   print "Email Sent successfully"
   try:
      update()
      print "Update Statement on Success code-block executed successfully
   except:
      connection.rollback()
      print "Update Statement failed and update Transaction Rolled back"
except SMTPException, e:
   print e+" SMTP ERROR OCCURED"
except Exception, e:
   print e
   print "Unexpected Error/Exception";
print "************************Python Script Log Ended at", localtime,"**********************"

此脚本计划通过 Windows 任务计划在 EC2 实例上运行。这个脚本通常工作得很好,但偶尔会吐出一条错误消息。错误信息如下:

************************Python Script Log Started at Thu Jun 07 03:40:04 2018 **********************
[Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Unexpected Error/Exception
************************Python Script Log Started at Thu Jun 07 03:40:04 2018 **********************

我试图复制这个错误但失败了。经过观察,我发现失败与失败时没有用户活动之间存在高度相关性。该脚本仅在 EC2 机器上没有最近的用户活动时才会失败。有没有人遇到过类似的事情?或任何建议/改进?

如果有任何缩进错误,请原谅,可能是由于我在将脚本复制到 StackOverflow 的降价时手动格式化。

4

1 回答 1

0

缺少错误消息的上下文,但这似乎表明您尝试连接的远程方。

您很可能会在异常对象中找到更详细的信息。我建议连接调试器或记录您的异常的更多详细信息,例如堆栈跟踪以查找违规行。

也许追溯在这里可能没有帮助。

于 2018-06-13T20:04:23.137 回答