Skip to content

Instantly share code, notes, and snippets.

@gh640 gh640/chmod.py
Last active May 25, 2019

Embed
What would you like to do?
Functions to add file permissions with Python.
# 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
You can’t perform that action at this time.