简体   繁体   English

是否存在从Python的OSError获取信息的跨平台方式?

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

On a simple directory creation operation for example, I can make an OSError like this: 例如,在一个简单的目录创建操作中,我可以像这样制作一个OSError:

(Ubuntu Linux) (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? 是否有一种跨平台的方式,我可以知道17或“文件存在”将始终意味着相同的事情,以便我可以根据情况采取不同的行动?

(This came up during another question .) (这是在另一个问题中出现的 。)

The errno attribute on the error should be the same on all platforms. errno属性应该在所有平台上都相同。 You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same " except OSError: " block will catch it. 您将在Windows上获得WindowsError异常,但由于这是OSError的子类,因此相同的“ except OSError: ”块将捕获它。 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. Windows确实有自己的错误代码,这些代码可以作为.winerror访问,但.errno属性应该仍然存在,并且可以跨平台方式使用。

Symbolic names for the various error codes can be found in the errno module. 可以在errno模块中找到各种错误代码的符号名称。 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 . 您还可以使用errno.errorcode执行反向查找(以查找应使用的代码)。 That is: 那是:

>>> errno.errorcode[17]
'EEXIST'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM