how to find the owner of a file or directory in python

前端 未结 7 1564
青春惊慌失措
青春惊慌失措 2020-12-03 04:38

I need a function or method in Python to find the owner of a file or directory.

The function should be like:

>>> find_owner(\"/home/somedir         


        
相关标签:
7条回答
  • 2020-12-03 05:20

    On Windows this Works but uses the cli

    import os
    from subprocess import Popen, PIPE
    from collections import namedtuple
    
    
    def sliceit(iterable, tup):
        return iterable[tup[0]:tup[1]].strip()
    
    def convert_cat(line):
        # Column Align Text indicies from cmd
        # Date time dir filesize owner filename
        Stat = namedtuple('Stat', 'date time directory size owner filename')
        stat_index = Stat(date=(0, 11), 
                          time=(11, 18), 
                          directory=(18, 27), 
                          size=(27, 35), 
                          owner=(35, 59), 
                          filename=(59, -1))
    
        stat = Stat(date=sliceit(line, stat_index.date),
                          time=sliceit(line, stat_index.time),
                          directory=sliceit(line, stat_index.directory),
                          size=sliceit(line, stat_index.size),
                          owner=sliceit(line, stat_index.owner),
                          filename=sliceit(line, stat_index.filename))
        return stat
    
    def stat(path):
        if not os.path.isdir(path):
            dirname, filename = os.path.split(path)
        else:
            dirname = path
        cmd = ["cmd", "/c", "dir", dirname, "/q"]
        session = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        # cp1252 is common on my Norwegian Computer,
        # check encoding from your windows system
        result = session.communicate()[0].decode('cp1252')
    
        if os.path.isdir(path):
            line = result.splitlines()[5]
            return convert_cat(line)
        else:
            for line in result.splitlines()[5:]:
                if filename in line:
                    return convert_cat(line)
            else:
                raise Exception('Could not locate file')
    
    if __name__ == '__main__':
        print(stat('C:\\temp').owner)
        print(stat('C:\\temp\\diff.py'))
    
    0 讨论(0)
提交回复
热议问题