Question

I have a python application that's accessing an ftp server. There are several error cases I'd like to catch in a fashion similar to httplib2:

try: 
    urllib2.urlopen("http://google.com")
except urllib2.HTTPError, e: 
    if e.code == 304: 
        #do 304 stuff
    if e.code == 404: 
        #do 404 stuff
    else: 
        pass 

Does a a construct like this exist in ftplib.err_perm? I know that could return a code of 500-599 according to the docs but I don't see anything in the docs about how to access that value. Did I miss something?

Was it helpful?

Solution

You can access error reponse string using <exception_obj>.args[0]. It contains strings like '550 /no-such-dir: No such file or directory'.

To get error code (only leading three chracters), use <exception_obj>.args[0][:3].

For example:

import ftplib
ftp = ftplib.FTP('ftp.hq.nasa.gov')
ftp.login('anonymous', 'user@example.com')
try:
    ftp.cwd('/no-such-dir')
except ftplib.error_perm as e:
    print('Error {}'.format(e.args[0][:3]))
finally:
    ftp.quit()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top