【问题标题】:How to get the owner and group of a folder with Python on a Linux machine?如何在 Linux 机器上使用 Python 获取文件夹的所有者和组?
【发布时间】:2010-10-29 23:55:24
【问题描述】:

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

【问题讨论】:

    标签: python linux directory owner


    【解决方案1】:

    从 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())
    

    【讨论】:

      【解决方案2】:

      使用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
      

      【讨论】:

        【解决方案3】:

        使用os.stat:

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

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

        【讨论】:

          【解决方案4】:

          使用os.stat 函数。

          【讨论】:

            【解决方案5】:

            我倾向于使用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 的链接中有一个示例。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-09-01
              • 1970-01-01
              • 2020-09-13
              • 1970-01-01
              • 1970-01-01
              • 2022-08-21
              • 1970-01-01
              • 2016-03-04
              相关资源
              最近更新 更多