在Python我們要判斷一個檔案對目前使用者有沒有讀、寫、執行權限,我們通常可以使用os.access函數來實現,例如:
# 判断读权限 os.access(<my file>, os.R_OK) # 判断写权限 os.access(<my file>, os.W_OK) # 判断执行权限 os.access(<my file>, os.X_OK) # 判断读、写、执行权限 os.access(<my file>, os.R_OK | os.W_OK | os.X_OK)
但如果要判斷任意一個指定的使用者對某個檔案是否有讀取、寫入、執行權限,Python中是沒有預設實現的,此時我們可以透過下面的程式碼斷來判斷
import os import pwd import stat def is_readable(cls, path, user): user_info = pwd.getpwnam(user) uid = user_info.pw_uid gid = user_info.pw_gid s = os.stat(path) mode = s[stat.ST_MODE] return ( ((s[stat.ST_UID] == uid) and (mode & stat.S_IRUSR > 0)) or ((s[stat.ST_GID] == gid) and (mode & stat.S_IRGRP > 0)) or (mode & stat.S_IROTH > 0) ) def is_writable(cls, path, user): user_info = pwd.getpwnam(user) uid = user_info.pw_uid gid = user_info.pw_gid s = os.stat(path) mode = s[stat.ST_MODE] return ( ((s[stat.ST_UID] == uid) and (mode & stat.S_IWUSR > 0)) or ((s[stat.ST_GID] == gid) and (mode & stat.S_IWGRP > 0)) or (mode & stat.S_IWOTH > 0) ) def is_executable(cls, path, user): user_info = pwd.getpwnam(user) uid = user_info.pw_uid gid = user_info.pw_gid s = os.stat(path) mode = s[stat.ST_MODE] return ( ((s[stat.ST_UID] == uid) and (mode & stat.S_IXUSR > 0)) or ((s[stat.ST_GID] == gid) and (mode & stat.S_IXGRP > 0)) or (mode & stat.S_IXOTH > 0) )
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。