如何按名称更改目录的用户和组权限?
os.chown 是我想要的功能,但我想通过名字来指定用户和组,而不是用ID(我不知道它们是什么)。我该怎么做呢?
4 个回答
5
因为shutil这个库的版本支持可选的组,所以我把代码复制粘贴到了我的Python2项目里。
https://hg.python.org/cpython/file/tip/Lib/shutil.py#l1010
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, basestring):
_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)
58
从Python 3.3开始,
你可以查看这个链接了解更多信息。
import shutil
shutil.chown(path, user=None, group=None)
这个功能可以改变指定路径的文件或文件夹的拥有者和/或所属的组。
这里的用户可以是系统中的用户名或者用户ID;组也是一样的。
至少需要提供一个参数。
这个功能只在Unix系统上可用。
128
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种特定的格式。
比如说,如果我们从用户那里获取了一些信息,这些信息可能是字符串(就是一串字符),但是我们想把它们变成数字,这样才能进行计算。这个过程就叫做“类型转换”。
在不同的编程语言中,类型转换的方式可能会有所不同。有的语言会自动帮你转换,有的则需要你手动去做。
总之,理解数据的类型和如何转换它们是编程中非常重要的一部分,这样才能让程序更好地工作。
import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = '/tmp/f.txt'
os.chown(path, uid, gid)