windows 在 Python 中测试目录权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/539133/
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
Test directory permissions in Python?
提问by Sean
In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at os.access
but it gives false results.
在 Windows 上的 Python 中,有没有办法确定用户是否有权访问目录?我已经看过了,os.access
但它给出了错误的结果。
>>> os.access('C:\haveaccess', os.R_OK)
False
>>> os.access(r'C:\haveaccess', os.R_OK)
True
>>> os.access('C:\donthaveaccess', os.R_OK)
False
>>> os.access(r'C:\donthaveaccess', os.R_OK)
True
Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?
难道我做错了什么?有没有更好的方法来检查用户是否有权访问目录?
采纳答案by dF.
It can be complicated to check for permissions in Windows (beware of issues in Vista with UAC, for example! -- see this related question).
在 Windows 中检查权限可能很复杂(例如,当心带有 UAC 的 Vista 中的问题! - 请参阅此相关问题)。
Are you talking about simple read access, i.e. reading the directory's contents?
The surest way of testing permissions would be to try to access the directory (e.g. do an os.listdir
) and catch the exception.
您是在谈论简单的读取访问,即读取目录的内容吗?测试权限最可靠的方法是尝试访问目录(例如执行os.listdir
)并捕获异常。
Also, in order for paths to be interpreted correctly you have to use raw strings or escape the backslashes ('\\'), -- or use forward slashes instead.
此外,为了正确解释路径,您必须使用原始字符串或转义反斜杠 ('\\'),或使用正斜杠代替。
(EDIT: you can avoid slashes altogether by using os.path.join
-- the recommended way to build paths)
(编辑:您可以使用os.path.join
-- 推荐的构建路径的方法来完全避免斜线)
回答by Theran
While os.access tries its best to tell if a path is accessible or not, it doesn't claim to be perfect. From the Python docs:
虽然 os.access 尽力判断路径是否可访问,但它并不声称是完美的。来自 Python 文档:
Note: I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.
注意:即使 access() 指示它们会成功,I/O 操作也可能会失败,特别是对于网络文件系统上的操作,其权限语义可能超出通常的 POSIX 权限位模型。
The recommended way to find out if the user has access to do whatever is to try to do it, and catch any exceptions that occur.
确定用户是否有权执行任何操作的推荐方法是尝试执行此操作并捕获发生的任何异常。
回答by Dan F
Actually 'C:\haveaccess' is different than r'C:\haveaccess'. From Python point of view 'C:\haveaccess' is not a valid path, so use 'C:\\haveaccess' instead. I think os.access works just fine.
实际上,'C:\haveaccess' 与 r'C:\haveaccess' 不同。从 Python 的角度来看,'C:\haveaccess' 不是有效路径,因此请改用 'C:\\haveaccess'。我认为 os.access 工作得很好。