Ftplib, how to handle exception without errno attribute?

I want to upload a file to the ftp site if the file is missing. This is the task of a more complex application, but in this case it is not important. My idea is to check if the file is present using the FTP.size(filename) method, and if the error is 550 (the system cannot find the specified file), upload the file.

My (doesn't work) code:

 from ftplib import * ftp = FTP("ftp.test.com", "user", "password") try: ftp.size("123.zip") except ftplib.all_errors, e: if e.errno == 550: print "UPLOAD" else: print str(e) 

Error returned:

 Traceback (most recent call last): File "<pyshell#106>", line 4, in <module> if e.errno == 550: AttributeError: 'error_perm' object has no attribute 'errno' 

or if a temporary error occurs:

 AttributeError: 'error_temp' object has no attribute 'errno' 

The only solution I found to manage the return code was the following:

 except ftplib.all_errors, e: if str(e.args[0]).split(" ", 1)[0] == "550": print "UPLOAD" else: print str(e) 

but I think there is a better solution because it only works if the error number is the first word in the exception message.

Thank you in advance!

+4
source share
2 answers

I don’t know exactly the properties of this error, so you can infer dir (e) when the except condition is activated. Then you will see all the error properties. One that almost doesn't work, since the flag is "error.message", which is a string, so you can build an if clause with this.

Would you end up with something like

 try: ftp.size("123.zip") except ftplib.all_errors as e: if e.message == 'message of the error' print 'UPLOAD' else: print str(e) 

By the way, a message is one thing you get when str (e) is executed.

+1
source

Perhaps this helps, from the documentation for ftplib.

Note that the SIZE command is not standardized, but is supported by many standard server implementations.

Link here

Try a different method to find out if the file is working.

0
source

All Articles