在python中支持POSIX openat函数 [英] Support for POSIX openat functions in python

查看:132
本文介绍了在python中支持POSIX openat函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个补丁可添加对POSIX

There is a patch to add support for the POSIX openat functions (and other *at functions like fstatat) to the python standard library that is marked as closed with resolution fixed, but the os, posix and platform modules do not currently include any of these methods.

这些方法是解决诸如

These methods are the standard way of solving problems like this in C and other languages efficiently and without race conditions.

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

Are these included in the standard library currently somewhere? And if not, are there plans to include this in the future.

推荐答案

是的,通过传递 os.open() :

Yes, this is supported by passing 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 [...]

此函数可以使用dir_fd参数支持相对于目录描述符的路径.

如果要使用高级文件对象,例如内置返回的对象,请 open() 函数,该函数的文档提供了示例代码,显示了如何使用该函数的opener参数来执行此操作.请注意,open()os.open()是完全不同的功能,请勿混淆.或者,您可以使用os.open()打开文件,然后将文件描述符号传递给

If you want to use high-level file objects such as those returned by the builtin 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() or to open().

还应该注意,这目前仅在Unix上有效;检查dir_fd支持的可移植且面向未来的方法是编写如下代码:

It should also be noted that this currently only works on Unix; the portable and future-proof way to check for dir_fd support is to write code such as the following:

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

另一方面,我不确定Windows是否甚至允许首先打开目录.您当然不能使用 /_wopen() ,如果给定路径是目录",则记录失败.为了安全起见,我建议您仅在检查dir_fd支持后才尝试打开目录.

On the other hand, I'm not entirely sure Windows even allows opening a directory in the first place. You certainly can't do it with _open()/_wopen(), which are documented to fail if "the given path is a directory." To be safe, I recommend only trying to open the directory after you check for dir_fd support.

这篇关于在python中支持POSIX openat函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆