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

dan*_*dan 16 python linux directory owner

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

Aym*_*ieh 33

使用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
Run Code Online (Sandbox Code Playgroud)


lox*_*axs 7

从 Python 3.4.4 开始,模块Pathpathlib为此提供了一个很好的语法:

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())
Run Code Online (Sandbox Code Playgroud)