April 8th, 2005, 05:19 PM
I'm new to Python, well versed in PHP and a bit of Perl.
I've written a simple backup utility that FTPs from one server to another. I'd like to implement exception handling on the FTP should someting go wrong.
This is basically what I have so far:
I'd like to use 'all_errors' documented here.html but I don't know how! Will I have to create a handler for each other exception?
ftp = FTP(ftp_host, ftp_user, ftp_pass)
ftp.storbinary('STOR ' + filename, pointer)
April 8th, 2005, 08:50 PM
ftp = ftplib.FTP('ftp.cwi.nl') # change to invalid address to test
# user anonymous, passwd anonymous@
ftp.retrlines('LIST') # change from LIST to invalid command to test
print "an error occured" #error message for any error.
here you go. make the changes to the right to test it out
Comments on this post
April 8th, 2005, 11:08 PM
Why use except ftplib.all_errors: when just plain old except is doing the same thing? Or can except ftplib.all_errors print out specific errors?
April 9th, 2005, 12:36 AM
A bare except does NOT do the same thing, as it will catch errors which it shouldn't (which is why, except in rare cases such top-level error handling/logging, you should not use them). For instance:
Originally Posted by †Yegg†
will always make abc 4. it would be much better if NameError were raised at this point. Bare excepts lead to subtle hard to track errors.
abc = 1
abc = do_something_with(acb)
abc = 4
Comments on this post
April 11th, 2005, 04:30 PM
I wanted to email myself the error when/if it happened, so this is what I ended up with:
ftp.storbinary("STOR " + filename, pointer)
except Exception, e:
err_msg = "Headers and stuff here"
for arg in e.args:
err_msg = err_msg + str(arg) + "\n"
from smtplib import SMTP
mFrom = 'alert@*.com'
mTo = myemail@***.com
mailer = SMTP('mail.***.com')
mailer.sendmail(mFrom, mTo, err_msg)
April 11th, 2005, 11:59 PM
That code won't work properly unless there's only one arg in e.args. If there's only one, use string formats:
Originally Posted by IceNine
If there's more than one, use a list comp and string formats:
err_header = "Header text\n"
err_body = "body intro: %s\n"%(e.args)
err_msg = err_header + err_body
err_header = "Header text"
err_body = ["body intro: %s"%(arg)
for arg in e.args]
err_msg = err_header + "".join(err_body)