Python determines a user's permissions on a file _python

Source: Internet
Author: User
Tags in python

In Python we have to determine whether a file has read, write, and execute permissions on the current user, and we can usually use the Os.access function for example:

# to Judge Read permission
os.access (<my file>, os. R_OK)
# judge Write permission
os.access (<my file>, os. W_OK)
# Judge execution Permissions
os.access (<my file>, os. X_OK)

# Judge Read, write, execute Permissions
os.access (<my file>, os. R_OK | Os. W_OK | Os. X_OK)

However, if you want to determine whether any of the specified users have read, write, and execute permissions on a file, there is no default implementation in Python, at which point we can use the following code to determine

Import OS import PWD import stat def is_readable (CLS, Path, user): User_info = Pwd.getpwnam (user) uid = USER_INFO.P W_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 g id = 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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.