如何在Linux机器上使用Python获取文件夹的所有者和组?

26

如何在Linux下使用Python获取目录的所有者和组ID?

6个回答

46

使用os.stat()获取文件的UID和GID。然后分别使用pwd.getpwuid()grp.getgrgid()函数获取用户和组名称。

import grp
import pwd
import os

stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid

user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group

13
自 Python 3.4.4 开始,pathlib 模块的 Path 类提供了一种很好的语法来实现此功能。
from pathlib import Path
whatever = Path("relative/or/absolute/path/to_whatever")
if whatever.exists():
    print("Owner: %s" % whatever.owner())
    print("Group: %s" % whatever.group())

1
使用 os.stat
>>> s = os.stat('.')
>>> s.st_uid
1000
>>> s.st_gid
1000

st_uid 是所有者的用户 ID,st_gid 是组 ID。有关可以通过 stat 获取的其他信息,请参阅链接的文档。


0

我倾向于使用 os.stat

在给定路径上执行一个 stat 系统调用。返回的值是一个对象,其属性对应于 stat 结构的成员,即:st_mode(保护位),st_ino(inode 号码),st_dev(设备),st_nlink(硬链接数目),st_uid(所有者用户ID),st_gid(所有者组ID)st_size(文件大小,以字节为单位),st_atime(最近访问时间),st_mtime(最近内容修改时间),st_ctime(平台相关;Unix 上最近元数据更改的时间,或 Windows 上的创建时间)

上面的链接中有一个关于 os.stat 的示例。


0
使用os.stat函数。

0
如果你使用的是Linux,那就简单多了。 用命令yum install tree安装tree。然后执行命令'tree -a -u -g'。

1
不是用Python写的。 - Arpad Horvath -- Слава Україні

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接