os.open 的误导性文档?



>我有以下内容:

$ ls -l a.txt 
-rw------- 1 root root 0 Mai 13 09:01 a.txt

我做到了以下几点:

$ python
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.open('a.txt', os.O_CREAT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'a.txt'
>>> 

这是在哪里记录的?不在这里,阿法克。唯一指定的是建议os.open是 C 运行时open系统调用的包装器,其中指出:

$ man 2 open
RETURN VALUE
open(), openat(), and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

那么,os.open的完整文档在哪里,包括可能引发的异常和返回值的详细说明?

您正在寻找open(2)"错误"部分:

ERRORS
The named file is opened unless:
[EACCES]           The requested access to the file is not allowed,
or search permission is denied for one of the
directories in the path prefix of pathname, or the
file did not exist yet and write access to the 
parent directory is not allowed.
[..]

在此列表中,特定于您的操作系统,您将找到可能出错的所有不同内容。要将其转换为 Python 异常,您可以查看内置异常列表;此处相关的所有异常都应继承自OSError: https://docs.python.org/3/library/exceptions.html#os-exceptions

每个单独的异常都列出了它对应的基础错误代码,因此您可以将其与可能错误的open(2)列表进行比较。 例如:

exceptionPermissionError
尝试在没有足够访问权限(例如文件系统权限(的情况下运行操作时引发。对应于错误EACCESEPERM

在实践中,大多数时候,你可能希望在open调用周围有一个包罗万象的except OSError块;如果你确实想只捕捉非常具体的异常,你可能不得不自己做一些实验。

最新更新