Last active
May 25, 2019 13:23
Star
You must be signed in to star a gist
Functions to add file permissions with Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
"""Provides functions to add file permissions. | |
read: | |
stat.S_IRUSR | |
stat.S_IRGRP | |
stat.S_IROTH | |
write: | |
stat.S_IWUSR | |
stat.S_IWGRP | |
stat.S_IWOTH | |
execute: | |
stat.S_IXUSR | |
stat.S_IXGRP | |
stat.S_IXOTH | |
""" | |
import stat | |
from pathlib import Path | |
def main(): | |
"""Test the functions.""" | |
add_read_permission(Path('sample1.txt'), 'go') | |
add_write_permission(Path('sample2.txt'), 'o') | |
add_execute_permission(Path('sample3.py'), 'ug') | |
def add_read_permission(path: Path, target: str = 'u'): | |
"""Add `r` (`read`) permission to specified targets.""" | |
mode_map = { | |
'u': stat.S_IRUSR, | |
'g': stat.S_IRGRP, | |
'o': stat.S_IROTH, | |
'a': stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH, | |
} | |
mode = path.stat().st_mode | |
for t in target: | |
mode |= mode_map[t] | |
path.chmod(mode) | |
def add_write_permission(path: Path, target: str = 'u'): | |
"""Add `w` (`write`) permission to specified targets.""" | |
mode_map = { | |
'u': stat.S_IWUSR, | |
'g': stat.S_IWGRP, | |
'o': stat.S_IWOTH, | |
'a': stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH, | |
} | |
mode = path.stat().st_mode | |
for t in target: | |
mode |= mode_map[t] | |
path.chmod(mode) | |
def add_execute_permission(path: Path, target: str = 'u'): | |
"""Add `x` (`execute`) permission to specified targets.""" | |
mode_map = { | |
'u': stat.S_IXUSR, | |
'g': stat.S_IXGRP, | |
'o': stat.S_IXOTH, | |
'a': stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH, | |
} | |
mode = path.stat().st_mode | |
for t in target: | |
mode |= mode_map[t] | |
path.chmod(mode) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment