使用 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 原文由 Ayman Hourieh 发布,翻译遵循 CC BY-SA 2.5 许可协议
自 Python 3.4.4 起, Path 类 pathlib 模块为此提供了一个很好的语法: 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()) 原文由 loxaxs 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
os.stat()
获取文件的 uid 和 gid。然后,使用pwd.getpwuid()
和grp.getgrgid()
分别获取用户名和组名。