tags:

views:

27

answers:

3

Trying to get a handle on the FTP library in Python. :)

Got this so far.

from ftplib import FTP

server = '127.0.0.1'
port = '57422'

print 'FTP Client (' + server + ') port: ' + port

try:
    ftp = FTP()
    ftp.connect(server, port, 3)
    print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'

    ftp.cwd('\\')

    x = '1'
    currentDir = ''

except: //***What do I put here?***

http://docs.python.org/library/ftplib.html says there are several error codes I can catch but I can't do

except: ftplib.all_errors

Second question. :P How can I retrieve more specific information on the error? Perhaps the error code?

Very new to python (an hour in or so).

+1  A: 

You write

except Exception, e:  #you can specify type of Exception also
   print str(e)
jcao219
+1  A: 

You dont want to try catch an Exception class unless you have to. Exception is a catch all, instead catch the specific class being thrown, socket.error

  import ftplib
  import socket <--

  server = '127.0.0.1'
  port = '57422'

  print 'FTP Client (' + server + ') port: ' + port

  ftp = ftplib.FTP()
  try:
    ftp.connect(server, port, 3)
    print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'

    ftp.cwd('\\')

    x = '1'
    currentDir = ''
  except socket.error,e: <--
    print 'unable to connect!,%s'%e
ebt
+2  A: 

I can't do

except: ftplib.all_errors

Of course not, that's simply bad syntax! But of course you can do it with proper syntax:

except ftblib.all_errors:

i.e., the colon after the tuple of exceptions.

How can I retrieve more specific information on the error? Perhaps the error code?

except ftplib.all_errors, e:
  errorcode_string = str(e).split(None, 1)

E.g., '530' will now be the value of errorcode_string when the complete error message was '530 Login authentication failed'.

Alex Martelli
name 'ftplib' is not defined when I try what you suggested (the original mistake was a typo)Not sure on what to do so far. I thought I had the 'namespace' imported already.
bobber205
@bobber, no, you need to add an `import ftplib` statement. You didn't import the **module** -- you only imported a class from within the module (a practice which I personally detest, but that's another issue); so, to access qualified names such as `ftplib.all_errors`, you _also_ need to `import ftplib`.
Alex Martelli