I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old
我使用的第三方库很好但不能按照我想要的方式处理不必要的文件。给它一个不存在的文件,而不是提高旧的
FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt'
it raises some obscure message:
它提出了一些模糊的信息:
OSError: Syntax error in file None (line 1)
I don't want to handle the missing file, don't want to catch nor handle the exception, don't want to raise a custom exception, neither want I to open
the file, nor to create it if it does not exist.
我不想处理丢失的文件,不想捕获也不想处理异常,不想引发自定义异常,既不希望我打开文件,也不想创建它,如果它不存在。
I only want to check it exists (os.path.isfile(filename)
will do the trick) and if not, then just raise a proper FileNotFoundError.
我只想检查它是否存在(os.path.isfile(filename)将执行该技巧)如果没有,那么只需引发一个正确的FileNotFoundError。
I tried this:
我试过这个:
#!/usr/bin/env python3
import os
if not os.path.isfile("nothing.txt"):
raise FileNotFoundError
what only outputs:
什么只输出:
Traceback (most recent call last):
File "./test_script.py", line 6, in <module>
raise FileNotFoundError
FileNotFoundError
This is better than a "Syntax error in file None", but how is it possible to raise the "real" python exception with the proper message, without having to reimplement it?
这比“文件无语法中的语法错误”更好,但如何用正确的消息引发“真正的”python异常,而不必重新实现它?
1 个解决方案
#1
37
Pass in arguments:
传递参数:
import errno
import os
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)
FileNotFoundError
is a subclass of OSError
, which takes several arguments. The first is an error code from the errno
module (file not found is always errno.ENOENT
), the second the error message (use os.strerror()
to obtain this), and pass in the filename as the 3rd.
FileNotFoundError是OSError的子类,它接受多个参数。第一个是来自errno模块的错误代码(找不到文件总是errno.ENOENT),第二个是错误消息(使用os.strerror()来获取它),并将文件名作为第3个传递。
The final string representation used in a traceback is built from those arguments:
回溯中使用的最终字符串表示形式是从这些参数构建的:
>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'
#1
37
Pass in arguments:
传递参数:
import errno
import os
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)
FileNotFoundError
is a subclass of OSError
, which takes several arguments. The first is an error code from the errno
module (file not found is always errno.ENOENT
), the second the error message (use os.strerror()
to obtain this), and pass in the filename as the 3rd.
FileNotFoundError是OSError的子类,它接受多个参数。第一个是来自errno模块的错误代码(找不到文件总是errno.ENOENT),第二个是错误消息(使用os.strerror()来获取它),并将文件名作为第3个传递。
The final string representation used in a traceback is built from those arguments:
回溯中使用的最终字符串表示形式是从这些参数构建的:
>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'