Python IOError 和 OSError 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29347790/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:27:01  来源:igfitidea点击:

Difference between IOError and OSError?

pythonexceptionpython-2.x

提问by Niklas R

I am always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised?

我总是对函数是否会引发 IOError 或 OSError (或两者兼而有之?)感到困惑。这些异常类型背后的主要规则是什么,它们之间有什么区别以及何时引发?

I've initially thought OSError is for things like permission denial, but opening a file without permissions will raise an IOError.

我最初认为 OSError 是针对权限拒绝之类的事情,但是在没有权限的情况下打开文件会引发 IOError。

采纳答案by Martijn Pieters

There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and removed IOErrorin Python 3 (it is now an alias for OSError). See PEP 3151 - Reworking the OS and IO exception hierarchy:

这两种类型之间的差异很小。事实上,即使是核心 Python 开发人员也同意没有真正的区别并IOError在 Python 3 中删除(它现在是 的别名OSError)。请参阅PEP 3151 - 重新设计 OS 和 IO 异常层次结构

While some of these distinctions can be explained by implementation considerations, they are often not very logical at a higher level. The line separating OSErrorand IOError, for example, is often blurry. Consider the following:

>>> os.remove("fff")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'fff'
>>> open("fff")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'fff'

虽然其中一些区别可以通过实现考虑来解释,但它们在更高级别上通常不是很合乎逻辑。例如,分隔OSError和的线IOError通常是模糊的。考虑以下:

>>> os.remove("fff")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'fff'
>>> open("fff")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'fff'

Yes, that's two different exception types with the exact same error message.

是的,这是具有完全相同错误消息的两种不同异常类型。

For your own code, stick to throwing OSError. For existing functions, check the documentation (it should detail what you need to catch), but you can safely catch both:

对于您自己的代码,请坚持使用 throw OSError。对于现有函数,请检查文档(它应该详细说明您需要捕获的内容),但您可以安全地捕获两者:

try:
    # ...
except (IOError, OSError):
    # handle error

Quoting the PEP again:

再次引用 PEP:

In fact, it is hard to think of any situation where OSErrorshould be caught but not IOError, or the reverse.

事实上,很难想出什么情况OSError应该被捕获而不能被捕获IOError,或者相反。