45

On a simple directory creation operation for example, I can make an OSError like this:

(Ubuntu Linux)

>>> import os
>>> os.mkdir('foo')
>>> os.mkdir('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'foo'

Now I can catch that error like this:

>>> import os
>>> os.mkdir('foo')
>>> try:
...     os.mkdir('foo')
... except OSError, e:
...     print e.args
... 
(17, 'File exists')

Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation?

(This came up during another question.)

Community
  • 1
  • 1
Ali Afshar
  • 40,967
  • 12
  • 95
  • 109

1 Answers1

60

The errno attribute on the error should be the same on all platforms. You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same "except OSError:" block will catch it. Windows does have its own error codes, and these are accessible as .winerror, but the .errno attribute should still be present, and usable in a cross-platform way.

Symbolic names for the various error codes can be found in the errno module. For example,

import os, errno
try:
    os.mkdir('test')
except OSError, e:
    if e.errno == errno.EEXIST:
        # Do something

You can also perform the reverse lookup (to find out what code you should be using) with errno.errorcode. That is:

>>> errno.errorcode[17]
'EEXIST'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brian
  • 116,865
  • 28
  • 107
  • 112
  • 8
    Probably a good idea to then reraise the original exception if it wasn't `EEXIST`. – ford Feb 27 '13 at 04:06
  • @ford Can you post an answer testing if directory exists first and then rerraising error after creation attempt? This is all seems overly complicated. In Linux I would use `mkdir -p ~/.config/mserve` for my purposes. I'm not sure what the `~` equivalent is in Windows though. It's hard to believe stack overflow doesn't have a definitive answer for creating a directory in Python... – WinEunuuchs2Unix Aug 18 '20 at 23:37
  • The first part of your question is answered here, I believe: https://stackoverflow.com/a/600612/576932 – ford Sep 11 '20 at 13:14