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.)
(这是在另一个问题中出现的。)
1 个解决方案
#1
52
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属性应该在所有平台上都相同。您将在Windows上获得WindowsError异常,但由于这是OSError的子类,因此相同的“除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'
#1
52
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属性应该在所有平台上都相同。您将在Windows上获得WindowsError异常,但由于这是OSError的子类,因此相同的“除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'