Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Functions to add file permissions with Python.
# coding: utf-8
'''Provides functions to add file permissions.
'''
import stat
from pathlib import Path
from functools import reduce
# 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
def main():
add_write_permission(Path('sample.txt'), 'o')
add_execute_permission(Path('sample.py'), 'ug')
def add_read_permission(path: Path, target='u': str):
'''Add "read" permission to specified targets.
'''
mode = path.stat().st_mode
mode_map = {
'u': stat.S_IRUSR,
'g': stat.S_IRGRP,
'o': stat.S_IROTH,
'a': stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH,
}
for t in target:
mode |= mode_map[t]
path.chmod(mode)
def add_write_permission(path: Path, target='u': str):
'''Add "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_additional = combine_permissions(target, mode_map)
path.chmod(path.stat().st_mode | mode_additional)
def add_execute_permission(path: Path, target='u': str):
'''Add "execute" permission to specified targets.
'''
mode = path.stat().st_mode
mode_map = {
'u': stat.S_IXUSR,
'g': stat.S_IXGRP,
'o': stat.S_IXOTH,
'a': stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH,
}
for t in target:
mode |= mode_map[t]
path.chmod(mode)
def combine_permissions(target: str, mode_map):
modes = map(lambda x: mode_map[x], target)
return reduce(lambda x, y: x | y, modes)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment