''' Creates error messages and a log file (.txt) Updated to send email to gis@cedarcounty.org Updated: 1/2/2012 by Caleb Mackey Cedar County, IA ''' import arcpy, os, sys, traceback, time import smtplib from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email import Encoders from datetime import datetime as d def SendErrorMessage(to_address): scriptname = sys.argv[0] # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = '\nPython Error Info:\n' + str(sys.exc_info()[1]) msgs = 'ArcPy ERRORS:\n' + arcpy.GetMessages(2) + '\n' # Create Log File desktop = os.path.join(os.environ['HOME'], 'Desktop') logs = os.path.join(desktop, 'Logs') # create log folder in desktop endTime = str(d.now()) Date = time.strftime('_%m_%d_%Y') usr = 'sentfrompython@gmail.com' # Create Text file and logs folder if not os.path.exists(logs): os.makedirs(logs) print logs txt = os.path.join(logs, os.path.basename(scriptname[:-3]) + Date + '.txt') print txt txtFile = open(txt, 'w') txtFile.write(scriptname + ' Failed at:\t%s' %endTime) txtFile.write('\nScript Fail time: %s\n' % endTime[:-7]) txtFile.write('\n\n%s\n\n%s' %(pymsg, msgs)) txtFile.close() # Send email emsg = MIMEText('%s Failed at:\t %s\n\n%s\n\n%s' %(scriptname,str(d.now()),pymsg,msgs)) emsg['Subject'] = '%s\tError' %os.path.basename(scriptname) s = smtplib.SMTP('smtp.gmail.com:587') s.starttls() pw = 'YourPassword' usr = 'sentfrompython@gmail.com' s.login(usr,pw) s.sendmail(usr,to_address,emsg.as_string()) s.quit()
import arcpy try: # do some geoprcoessing tasks # do arcpy stuff kjlkjk # this will raise an error and send email message except: import Gmail_tools Gmail_tools.SendErrorMessage('caleb.mackey@gmail.com') # sends message to my gmail account
C:/Users/Caleb/Desktop/email_test.py Failed at: 2013-12-14 13:42:49.228000
Script Fail time: 2013-12-14 13:42:49
Python Error Info:
name 'kjlkjk' is not defined
ArcPy ERRORS:
did you figure this out?
At the end of my Python script I have a section of code that creates a completion status message and emails it stating that everything was completed successfully. I also have one that sends an error message if something does not.
You could change the code so that it creates the txt message initially and then write to it each time a FC has been created. Upon an error, add the error message to the same text and then email it to yourself.
George
# Import arcpy module
import arcpy,sys,traceback,smtplib
from arcpy import env
#NOTE you can ignore some of these modules, only import the ones needed, some of these are for the other portion of my script
import httplib,urllib,json,getpass,csv,xlwt
import xml.dom.minidom as DOM
from email.mime.text import MIMEText
msgFolder = "C:/arcgisserver/gisData/services/claimsMap/logs/"
sender = "YOUR INFO"
recipient = "YOUR INFO"
#########################################################
##### Main Code Body #####
while True:
try:
######################################################
### Results Email Message #####
### Create Email Status Message
msgTxt = msgFolder+"resultMSG.txt"
writeFile = open(msgTxt,"w")
writeFile.write("claimsMaps are now updated.\n")
writeFile.write("\n")
writeFile.write("Verify the current mapservice and refresh as needed.\n")
writeFile.write("\n")
writeFile.close()
del msgTxt
### Send Email Status Message
txt = msgFolder+"resultMSG.txt"
fp = open(txt,'rb')
msg = MIMEText(fp.read())
fp.close()
msg['Subject'] = "claimsMaps Updated"
msg['From'] = sender
msg['To'] = recipient
server = smtplib.SMTP("YOUR INFO")
server.sendmail(sender,recipient,msg.as_string())
server.quit()
del txt
#######################################################
except Exception:
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str(sys.exc_type) + ": " + str(sys.exc_value) + "\n"
msgs = "ARCPY ERRORS:\n" + arcpy.GetMessages(2) + "\n"
print msgs
print pymsg
print arcpy.GetMessages(1)
### Create Email Error Message
msgTxt = msgFolder+"errorArcMSG.txt"
writeFile = open(msgTxt,"w")
writeFile.write("claimsMap Error Msg\n")
writeFile.write("\n")
writeFile.write("claimsMap Script Failure\n")
writeFile.write(msgs+"\n")
writeFile.write("\n")
writeFile.write(pymsg+"\n")
writeFile.write("\n")
writeFile.write(arcpy.GetMessages(1))
writeFile.close()
### Send Email Status Message
fp = open(msgTxt,'rb')
msg = MIMEText(fp.read())
fp.close()
msg['Subject'] = "claimsMap Script Error"
msg['From'] = sender
msg['To'] = recipient
server = smtplib.SMTP("YOUR INFO")
server.sendmail(sender,recipient,msg.as_string())
server.quit()
print "Preparing to restart script due to processing error..."
pass
else:
break