是否有跨平台的方式从Python的OSError获取信息? [英] Is there a cross-platform way of getting information from Python's OSError?

查看:478
本文介绍了是否有跨平台的方式从Python的OSError获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在简单的目录创建操作中,我可以像这样做一个OSError:

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

(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')

有一种跨平台的方式,我可以知道17或档案存在者总是意味着相同的事情,以便我可以根据情况采取不同的行动。

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?

(这是一个另一个问题) p>

(This came up during another question.)

推荐答案

错误中的 errno 属性在所有平台上都应该相同。您将在Windows上获得 WindowsError 异常,但由于这是OSError的子类,所以除了OSError:块会抓住它Windows有自己的错误代码,这些代码可以 .winerror 访问,但$ code> .errno 属性应该仍然是

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 模块。
例如,

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

您还可以使用 errno.errorcode 执行反向查找(以查找应该使用的代码)。那就是:

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'

这篇关于是否有跨平台的方式从Python的OSError获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆