This article describes in detail how Python judges a user's permissions on a file, which has some reference value, if you are interested, you can refer to Python to determine whether a file has read, write, and execution permissions for the current user. we usually use the OS. for example:
# Judge the read permission OS. access (
, OS. R_ OK) # judge the write permission OS. access (
, OS. W_ OK) # judge the execution permission OS. access (
, OS. X_ OK) # judge read, write, and execute permissions for OS. access (
, OS. R_ OK | OS. W_ OK | OS. X_ OK)
However, if you want to determine whether a specified user has the read, write, and execution permissions on a file, Python does not implement this by default. in this case, you can use the following code to determine whether a specified user has the read, write, and execution permissions on the file.
import osimport pwdimport 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) )
The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own home.