描述
方法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() 的模式參數中的值,用於測試路徑的可讀性。
os.W_OK− 包含在 access() 的模式參數中的值,用於測試路徑的可寫性。
os.X_OK− 包含在 access() 的模式參數中以確定路徑是否可以執行的值。
返回值
如果允許訪問,則此方法返回 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)
結果
當我們運行上述程序時,它會產生以下結果 -
F_OK - return value True R_OK - return value True W_OK - return value True X_OK - return value False
相關用法
- Python 3 os.fstatvfs()用法及代碼示例
- Python 3 os.minor()用法及代碼示例
- Python 3 os.close()用法及代碼示例
- Python 3 os.unlink()用法及代碼示例
- Python 3 os.major()用法及代碼示例
- Python 3 os.rmdir()用法及代碼示例
- Python 3 os.fdopen()用法及代碼示例
- Python 3 os.fdatasync()用法及代碼示例
- Python 3 os.isatty()用法及代碼示例
- Python 3 os.rename()用法及代碼示例
- Python 3 os.walk()用法及代碼示例
- Python 3 os.renames()用法及代碼示例
- Python 3 os.makedirs()用法及代碼示例
- Python 3 os.utime()用法及代碼示例
- Python 3 os.tcgetpgrp()用法及代碼示例
- Python 3 os.statvfs()用法及代碼示例
- Python 3 os.lchown()用法及代碼示例
- Python 3 os.mknod()用法及代碼示例
- Python 3 os.lstat()用法及代碼示例
- Python 3 os.tmpfile()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - os.access() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。