是否有跨平台的方式从 Python 的 OSError 获取信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/273698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a cross-platform way of getting information from Python's OSError?
提问by Ali Afshar
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.)
(这是在另一个问题中提出的。)
回答by Brian
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.
errno
错误的属性在所有平台上都应该相同。您将WindowsError
在 Windows 上获得异常,但由于这是 OSError 的子类,因此相同的 " except OSError:
" 块将捕获它。Windows 确实有自己的错误代码,这些代码可以作为 访问.winerror
,但该.errno
属性应该仍然存在,并且可以跨平台方式使用。
Symbolic names for the various error codes can be found in the errno
module.
For example,
可以在errno
模块中找到各种错误代码的符号名称。例如,
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
. 那是:
>>> errno.errorcode[17]
'EEXIST'