[New-bugs-announce] [issue25790] shutil.chown function enhancement
YoSTEALTH
report at bugs.python.org
Thu Dec 3 15:27:33 EST 2015
New submission from YoSTEALTH:
A very simple but useful enhancement for shutil.chown function
Currently "shutil.chown" function effects only one directory or file user/group permission by adding "recursive" parameter it can easily effect all sub-directories/files
Source: https://hg.python.org/cpython/file/3.5/Lib/shutil.py#l1007
# Current:
def chown(path, user=None, group=None):
"""Change owner user and group of the given path.
user and group can be the uid/gid or the user/group names, and in that case,
they are converted to their respective uid/gid.
"""
if user is None and group is None:
raise ValueError("user and/or group must be set")
_user = user
_group = group
# -1 means don't change it
if user is None:
_user = -1
# user can either be an int (the uid) or a string (the system username)
elif isinstance(user, str):
_user = _get_uid(user)
if _user is None:
raise LookupError("no such user: {!r}".format(user))
if group is None:
_group = -1
elif not isinstance(group, int):
_group = _get_gid(group)
if _group is None:
raise LookupError("no such group: {!r}".format(group))
os.chown(path, _user, _group)
# Enhanced:
import os.path
# Internal Function
def _dir_walk(path):
''' Get All Directories & Files'''
for dir_path, dir_names, file_names in os.walk(path):
# Directories
for dir_name in dir_names:
yield os.path.join(dir_path, dir_name)
# Files
for file_name in file_names:
yield os.path.join(dir_path, file_name)
def chown(path, user=None, group=None, recursive=False):
"""Change owner user and group of the given path.
user and group can be the uid/gid or the user/group names, and in that case,
they are converted to their respective uid/gid.
"""
if user is None and group is None:
raise ValueError("user and/or group must be set")
_user = user
_group = group
# -1 means don't change it
if user is None:
_user = -1
# user can either be an int (the uid) or a string (the system username)
elif isinstance(user, str):
_user = _get_uid(user)
if _user is None:
raise LookupError("no such user: {!r}".format(user))
if group is None:
_group = -1
elif not isinstance(group, int):
_group = _get_gid(group)
if _group is None:
raise LookupError("no such group: {!r}".format(group))
# Default Do First
if not recursive:
os.chown(path, _user, _group)
else:
for recursive_path in _dir_walk(path):
os.chown(recursive_path, _user, _group)
hope this helps :)
----------
hgrepos: 324
messages: 255834
nosy: YoSTEALTH
priority: normal
severity: normal
status: open
title: shutil.chown function enhancement
type: enhancement
versions: Python 3.5
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue25790>
_______________________________________
More information about the New-bugs-announce
mailing list