views:

55

answers:

2

I need to obtain the error number from an error that has occurred in Python. Ex; When trying to transfer a directory via the Paramiko package, an error is caught with this piece of code:

            try:
        sftp.put(local_path,target_path)
    except (IOError,OSError),errno:
        print "Error:",errno

For which I get the output,

        Error: [Errno 21] Is a directory

I want to utilize the error number to go into some more code to transfer the directory and the directory contents.

+1  A: 

Thanks for clarifying your question.

Most Exceptions in Python don't have "error numbers". One exception (no pun intended) are HTTPError exceptions, for example:

import urllib2 
try:
   page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
   if err.code == 404:
       print "Page not found!"
   else:
       ...

Another exception (as noted by bobince) are EnvironmentErrors:

import os
try:
   f=open("hello")
except IOError, err:
   print err
   print err.errno
   print err.strerror
   print err.filename

outputs

[Errno 2] No such file or directory: 'hello'
2
No such file or directory
hello
Tim Pietzcker
This was exactly what I was looking for!Thanks, Tim.
fixxxer
+2  A: 

If you're talking about errno.h error numbers, you can get them from the errno property on the exception object, but only on EnvironmentError (which includes OSError, IOError and WindowsError).

Specifically on WindowsError you'll also get a winerror property with a Windows-specific error number. (You don't often see one of these though, as Python uses the Win32 API directly relatively rarely.)

bobince