如何从 Python 3 导入 FileNotFoundError?

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

How do I import FileNotFoundError from Python 3?

pythonpython-2.7exceptionpython-3.x

提问by PSNR

I am currently using Python 2 on a project that needs a Python 3 built-in exception: FileNotFoundError. How do I do it?

我目前正在一个需要 Python 3 内置异常的项目上使用 Python 2:FileNotFoundError. 我该怎么做?

采纳答案by abarnert

You can of course define any exceptions you want.

您当然可以定义您想要的任何异常。

But they're not going to do you any good. The whole point of FileNotFoundErroris that any Python operation that runs into a file-not-found error will raise that exception. Just defining your own exception won't make that true. All you're going to get is an OSError(or IOError, depending on 2.x version) with an appropriate errnovalue. If you try to handle a custom FileNotFoundError, your handler will never get called.

但他们不会对你有任何好处。重点FileNotFoundError是任何遇到文件未找到错误的 Python 操作都会引发该异常。仅定义您自己的异常不会使这一点成为现实。您将获得的只是一个OSError(或IOError,取决于 2.x 版本)具有适当errno值。如果您尝试处理 custom FileNotFoundError,您的处理程序将永远不会被调用。

So, what you really want is (for example):

所以,你真正想要的是(例如):

try:
    f = open(path)
except OSError as e:
    if e.errno == errno.ENOENT:
        # do your FileNotFoundError code here
    else:
        raise

回答by PSNR

You can simply create the FileNotFoundErrorexception yourself:

您可以简单地FileNotFoundError自己创建异常:

class FileNotFoundError(OSError):
    pass

This new exception class inherits from OSErrorjust like the one in Python 3.x.

这个新的异常类继承自OSErrorPython 3.x 中的异常类。

Here is a reference on User-defined Exceptionsin Python.

这是有关Python 中用户定义的异常的参考。

回答by Martin Thoma

You could use IOErrorinstead:

你可以IOError改用:

Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, e.g., “file not found”or “disk full”.

This class is derived from EnvironmentError. See the discussion above for more information on exception instance attributes.

Changed in version 2.6: Changed socket.error to use this as a base class.

当 I/O 操作(例如打印语句、内置 open() 函数或文件对象的方法)因 I/O 相关原因失败时引发,例如“找不到文件”或“磁盘满的”。

此类派生自 EnvironmentError。有关异常实例属性的更多信息,请参阅上面的讨论。

在 2.6 版更改:将 socket.error 更改为将其用作基类。

回答by cowlinator

Short answer: Just use EnvironmentErrorand check err.errno == errno.ENOENTfor either Python 2 or Python 3.

简短回答: 只需使用EnvironmentError并检查err.errno == errno.ENOENTPython 2 或 Python 3。

Long answer:

长答案:

As other answers have mentioned, FileNotFoundErroris new to Python 3.

正如其他答案所提到的,FileNotFoundError是 Python 3 的新手。

Python 2 used OSError(or IOError, depending on 2.x version). OSErrorand IOErrorboth inherit from EnvironmentError.

使用 Python 2 OSError(或IOError,取决于 2.x 版本)。 OSError并且IOError都继承自EnvironmentError.

In Python 3, EnvironmentErroris aliased to OSError. FileNotFoundErrorinherits from OSError, which means that FileNotFoundErrorcan be caught with EnvironmentError, and it shares the same interface as OSErrorand IOError.

在 Python 3 中,EnvironmentError别名为OSError. FileNotFoundError从继承OSError,这意味着FileNotFoundError可以与被捕获EnvironmentError,而且这股相同的接口OSErrorIOError

So, good news! This means that there is a relatively easy way to make your project compatible with both Python 2 and Python 3 at the same time: leave FileNotFoundErrorout of it, and just catch EnvironmentError.

所以,好消息!这意味着有一种相对简单的方法可以使您的项目同时与 Python 2 和 Python 3 兼容:FileNotFoundError不使用它,只使用 catch EnvironmentError

# Works for Python 2.  Also works for Python 3.
import errno

try:
    open("fake.file", 'r')
except EnvironmentError as err:
    if err.errno == errno.ENOENT: # ENOENT -> "no entity" -> "file not found"
        print("Caught 'file not found' exception")
    else:
        raise