【问题标题】:check permissions of directories in python检查python中目录的权限
【发布时间】:2009-04-01 10:35:37
【问题描述】:

我想要一个给定目录的 python 程序,它将返回该目录中具有 775 (rwxrwxr-x) 权限的所有目录

谢谢!

【问题讨论】:

    标签: python chmod


    【解决方案1】:

    看看os 模块。特别是os.stat 查看权限位。

    import  os
    
    for filename in os.listdir(dirname):
       path=os.path.join(dirname, filename)
       if os.path.isdir(path):
           if (os.stat(path).st_mode & 0777) == 0775:
               print path
    

    【讨论】:

    • 你可以使用 "if os.path.isdir(path) and (os.stat(path).st_mode & 0777) == 0775:" 而不是两个 ifs 使它更紧凑并且仍然可读.
    【解决方案2】:

    一定是python吗?

    您也可以使用 find 来做到这一点:

    "找到 .-perm 775"

    【讨论】:

      【解决方案3】:

      这两个答案都不会重复,尽管这并不完全清楚这就是 OP 想要的。这是一种递归方法(未经测试,但您明白了):

      import os
      import stat
      import sys
      
      MODE = "775"
      
      def mode_matches(mode, file):
          """Return True if 'file' matches 'mode'.
      
          'mode' should be an integer representing an octal mode (eg
          int("755", 8) -> 493).
          """
          # Extract the permissions bits from the file's (or
          # directory's) stat info.
          filemode = stat.S_IMODE(os.stat(file).st_mode)
      
          return filemode == mode
      
      try:
          top = sys.argv[1]
      except IndexError:
          top = '.'
      
      try:
          mode = int(sys.argv[2], 8)
      except IndexError:
          mode = MODE
      
      # Convert mode to octal.
      mode = int(mode, 8)
      
      for dirpath, dirnames, filenames in os.walk(top):
          dirs = [os.path.join(dirpath, x) for x in dirnames]
          for dirname in dirs:
              if mode_matches(mode, dirname):
                  print dirname
      

      stdlib 文档中描述了类似的内容 stat.

      【讨论】:

      • 好的解决方案,您可以使用 int(sys.argv[2], 8) 直接转换用户八进制,而不是在函数内部使用 stat 返回
      • 啊——确实!我已经更新了我的答案,将所需的模式转换为八进制,而不是为每个发现的模式反过来。谢谢!
      • 你也可以直接写八进制数,如果你在它们前面放一个 0,例如0777 计算结果为 511,与 int("777", 8) 相同
      【解决方案4】:

      基于 Brian 回答的紧凑型生成器:

      import os
      
      (fpath for fpath 
         in (os.path.join(dirname,fname) for fname in os.listdir(dirname)) 
         if (os.path.isdir(fpath) and (os.stat(fpath).st_mode & 0777) == 0775))
      

      【讨论】:

        【解决方案5】:

        您可以使用以下命令检查文件和目录的 775 权限

        path="location of file or directory"
        if (oct(os.stat(path).st_mode)[-3:]=="775"):
            print(path)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-20
          • 2010-09-25
          • 1970-01-01
          • 1970-01-01
          • 2010-09-16
          • 1970-01-01
          相关资源
          最近更新 更多