Assuming it's a Win32 error code, winerror.h from the Platform SDK holds
the answer. One version is linked below, it's in theory out of date
(2003) but all the best known codes are present.
http://msdn.microsoft.com/en-us/library/ms819773.aspx
http://msdn.microsoft.com/en-us/library/ms819775.aspx
For example, "WindowsError [error 5] Access is denied" matches
ERROR_ACCESS_DENIED (5L).
HRESULTS may also crop up (e.g. E_FAIL, 0x80040005) which are harder to
list exhaustively since subsystems and COM components may roll their own
codes of various sorts; but common ones are present in winerror.h.
All the best,
-eg.
Ultimately, only MSDN can tell you :)
But to be going on with, a combination of Python's built-in errno
module:
http://docs.python.org/library/errno.html
and the pywin32 package's winerror module:
http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/file/236b256c13bf/win32/Lib/winerror.py
should help
TJG
Since Python 2.5, the errno attribute maps the Windows error to error
codes that match the attributes of module errno.
http://docs.python.org/library/exceptions.html#exceptions.WindowsError
So for some purposes you can use the same UNIXy error codes you can use
on most other platforms. Example:
import errno
try:
operation()
except WindowsError, exc:
if exc.errno != errno.ENOENT:
raise
print "file/directory does not exist"
Obviously whether this is useful depends on the error cases you need to
handle.
Undocumented: when there's no useful mapping to errno, you get
errno.EINVAL.
John
Good point, I completely misread that. At least the Windows error code
is still available as the winerror attribute.
As an aside - call me stupid, but I don't quite follow the purpose of
that errno mapping. Surely if the error number can be mapped
successfully then the error isn't Windows specific and an OSError should
logically be thrown instead? And if it can't be mapped successfully then
errno will never be valid so the mapping is pointless?
I guess if the mapping is imprecise then it makes some sense as errno is
a convenience to avoid people having to grasp the meaning of the many
and various winerror.h values. So perhaps I've answered my own question.
> def find_win_error_no(error_msg):
> """
> error_msg is a string with the error message - typically
> sys.exc_info()[1] from a WindowsError exception
> Returns the number as a string, not an int
> """
> win_error_re = re.compile('\[Error \d{1,5}\]')
> win_error_num_re = re.compile('\d{1,5}')
> win_error = win_error_re.findall(error_msg)[0]
> return win_error_num_re.findall(win_error)[0]
I call it here:
> def make_prog_dir(dir):
> try:
> os.mkdir(dir)
> except WindowsError:
> error_info = str(sys.exc_info()[1])
> num = find_win_error_no(error_msg=error_info)
> if num == '183': # Error 183 = 'Cannot create a file when that
> file already exists'
> logger.debug(dir + ' exists.') # Ignore the error, but
> make a note
> elif num == '5': # Error 5 = 'Access is denied'
> logger.critical('Could not create', dir, '\(access denied\).')
> else:
> logger.critical('Could not create', dir, '-', error_info)
Errors 183 and 5 are going to be the most common, but I'll look at the
lists on MSDN to see if there's anything else worth adding (and
familiarize myself with any more common errors).
>
> > Andrew Berg<bahamutzero8825 <at> gmail.com> writes:
> > Since Python 2.5, the errno attribute maps the Windows error to error
> > codes that match the attributes of module errno.
>
> Good point, I completely misread that. At least the Windows error code
> is still available as the winerror attribute.
>
> As an aside - call me stupid, but I don't quite follow the purpose of
> that errno mapping. Surely if the error number can be mapped
> successfully then the error isn't Windows specific and an OSError should
> logically be thrown instead? And if it can't be mapped successfully then
> errno will never be valid so the mapping is pointless?
Since WindowsError is a subclass of OSError, .errno has to be there (and it must
contain the UNIXy error code). You could then ask why it's a subclass in the
first place. I think part of the answer is that the docs are wrong --
presumably actual usage is that WindowsError is raised when a Windows API call
is made that *may* result in an exception that has no corresponding errno value
("presumably" because I'm writing on Linux & sourceforge is too slow for me
today to grab pywin32). In other words, code that raises WindowsError doesn't
try to test the error code so that it can raise OSError instead some of the
time. I don't think there would be any benefit in doing that, and it would have
the disadvantage that with those calls, you'd have to deal with a mixture of
Windows and UNIXy error codes.
The presence of .errno, aside from being required (to satisfy LSP), does mean
you don't have to deal with the Windows codes if you're only interested in cases
covered by module errno.
John
On Windows, you can use ctypes.FormatError(code) to map error codes
to strings:
>>> import ctypes
>>> ctypes.FormatError(32)
'Der Prozess kann nicht auf die Datei zugreifen, da sie von einem
anderen Prozess verwendet wird.'
>>>
For HRESULT codes, you (unfortunately) have to subtract 2**32-1 from
the error code:
>>> ctypes.FormatError(0x80040005)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int
>>> ctypes.FormatError(0x80040005 - (2**32-1))
'Kein Cache zum Verarbeiten vorhanden.'
>>>
Thomas
sys.exc_info() is how I get the error code from inside an except clause
in the first place. Or is there something I'm missing here?