Is there a cross-platform way of getting information from Python's OSError?

前端 未结 1 1260
长情又很酷
长情又很酷 2020-12-24 01:35

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

(Ubuntu Linux)

>>> import os
>>> os.mkdir(\'         


        
1条回答
  •  礼貌的吻别
    2020-12-24 01:50

    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'
    

    0 讨论(0)
提交回复
热议问题