在 python 中支持 POSIX openat 函数

Support for POSIX openat functions in python

python 标准库中有一个 patch to add support for the POSIX openat functions (and other *at functions like fstatat) 标记为 closed,分辨率为 fixed,但是 osposixplatform 模块目前不包含任何这些方法。

这些方法是在 C 和其他语言中有效解决 this 等问题的标准方法,并且没有竞争条件。

这些是否包含在当前某个地方的标准库中?如果没有,未来是否有计划将其包括在内。

是的,通过 the dir_fd argument to various functions in the standard os module. See for example os.open():

支持

Open the file path and set various flags [...]

This function can support paths relative to directory descriptors with the dir_fd parameter.

如果您想使用高级文件对象,例如 内置函数 open() function, that function's documentation provides example code showing how to do this using the opener parameter to that function. Note that open() and os.open() are entirely different functions and should not be confused. Alternatively, you could open the file with os.open() and then pass the file descriptor number to os.fdopen()open().

返回的那些

还需要注意的是,这目前仅适用于 Unix;检查 dir_fd 支持的可移植且面向未来的方法是编写如下代码:

if os.open in os.supports_dir_fd:
    # Use dir_fd.
else:
    # Don't.

另一方面,我不完全确定 Windows 是否允许首先打开一个目录。你当然不能用 _open()/_wopen() 来做到这一点,如果“给定路径是一个目录”,它被记录为失败。为了安全起见,我建议您在检查 dir_fd 支持后才尝试打开目录。