Sunday, April 17, 2011

check permissions of directories in python

hi i want a python program that given a directory, it will return all directories within that directory that have 775 (rwxrwxr-x) permissions

thanks!

From stackoverflow
  • Does it have to be python?

    You can also use find to do that :

    "find . -perm 775"

  • Take a look at the os module. In particular os.stat to look at the permission bits.

    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
    
    nosklo : You could make it more compact and still readable using "if os.path.isdir(path) and (os.stat(path).st_mode & 0777) == 0775:" instead of two ifs.
  • Neither answer recurses, though it's not entirely clear that that's what the OP wants. Here's a recursive approach (untested, but you get the idea):

    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
    

    Something similar is described in the stdlib documentation for stat.

    nosklo : good solution, you could use int(sys.argv[2], 8) to convert the user octal directly instead of doing it inside the function with the return from stat
    lt_kije : Ah -- indeed! I've updated my answer to convert the desired mode to octal instead of going the other way around for every discovered mode. Thanks!
  • Compact generator based on Brian's answer:

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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.