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