Python os.access()
方法方法使用真实的uid/gid
来测试访问路径。大多数操作将使用有效的uid/gid
,因此该例程可以在suid/sgid
环境中使用,以测试调用用户是否具有指定的访问权限。如果允许访问则返回True
,否则返回False
。
语法
以下是access()
方法的语法 -
os.access(path, mode)
参数
- path − 这是文件中读/写指针的位置。
- mode − 这应该是
F_OK
,用来测试路径的存在,或者它可以是R_OK
,W_OK
和X_OK
中的一个或多个的包含OR
来测试权限。os.F_OK
- 作为access()
的mode
参数传递的值以测试路径的存在。os.R_OK
- 包含在access()
的mode
参数中的值,以测试路径的可读性。os.W_OK
- 要包含在access()
的mode
参数中的值,以测试路径的可写性。os.X_OK
- 要包含在access()
的mode
参数中的值,以确定是否可以执行路径。
返回值
- 如果允许访问,此方法返回
True
,否则返回False
。
示例
以下示例显示了access()
方法的用法。
#!/usr/bin/python3
import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions.
ret = os.access("/tmp/foo.txt", os.F_OK)
print ("F_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.R_OK)
print ("R_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.W_OK)
print ("W_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.X_OK)
print ("X_OK - return value %s"% ret)
执行上面代码后,将得到以下结果 -
Name of the file: foo.txt
F_OK - return value True
R_OK - return value True
W_OK - return value True
X_OK - return value False