Monday, March 12, 2012
Tuesday, March 6, 2012
Sending Email At the End of Your Process
Here is a nice script that will allow you to send emails at the end of your python script, or where ever you want to. Today I just posted a comment on my topic of long running scripts, and I am adding this component onto my workflow, so I know when processes finish or that they have completed.
Enjoy
Enjoy
import arcpy
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(send_from, send_to,
subject, text,
f="",server="THE SERVER URL"):
assert type(send_to)==list
# Provide the name of your email server below
#
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
if os.path.isfile(f):
part = MIMEBase('application', "zip")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
def trace():
import traceback
import inspect
import sys
'''
trace finds the line, the filename and error message and returns it
to the user
'''
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# script name + line number
line = tbinfo.split(", ")[1]
filename = inspect.getfile( inspect.currentframe() )
# Get Python syntax error
#
synerror = traceback.format_exc().splitlines()[-1]
return line, filename, synerror
def main(*argv):
try:
# User Inputs
#
server = argv[0]
subject = argv[1]
message = argv[2]
recievers = str(argv[3]).split(';')
# Email Function
#
send_mail(
"NOTIFICATION@DONOTREPLY.COM",
recievers,
subject,
message,
"",
server)
arcpy.SetParameterAsText(4,True)
except:
arcpy.AddError(arcpy.GetMessages(2))
arcpy.AddError(str(trace()))
arcpy.SetParameterAsText(4,False)
if __name__ == "__main__":
argv = tuple(arcpy.GetParameterAsText(i)
for i in range(arcpy.GetArgumentCount()))
main(*argv)
Thursday, March 1, 2012
Clean Up Files - A Helpful Function
I've been developing window services using python (win32api), and often I find is necessary that I need to clean up files at the end of the process. I developed a small function that is quite helpful for cleaning up files by extension:
def cleanUpFiles(directory,extension):
dir = directory
files = os.listdir(dir)
for f in files:
if not os.path.isdir(f) and extension in f:
os.remove(dir + os.sep + f)
Enjoy
Subscribe to:
Posts (Atom)