如何在Linux下使用Python获取目录的所有者和组ID?
使用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
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())
>>> s = os.stat('.')
>>> s.st_uid
1000
>>> s.st_gid
1000
st_uid
是所有者的用户 ID,st_gid
是组 ID。有关可以通过 stat
获取的其他信息,请参阅链接的文档。
我倾向于使用 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
的示例。
os.stat
函数。