-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathls.py
executable file
·84 lines (73 loc) · 2.1 KB
/
ls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
# encoding: utf-8
import os
import stat
import pwd
import grp
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("path", default=".", nargs="?")
parser.add_argument("-a", "--all", action="store_true")
parser.add_argument("-l", "--long", action="store_true")
args = parser.parse_args()
def ls():
path = args.path
if args.all:
listdir = os.listdir(path)
else:
listdir = [f for f in os.listdir(path) if not f.startswith(".")]
listdir.sort()
output = ""
if args.long:
output = longlist(path, listdir)
else:
output = defOutput(listdir)
print output
def defOutput(listdir):
output = ""
for filename in listdir:
output += filename + " "
return output
def longlist(argPath, listdir):
output = ""
for filename in listdir:
filepath = os.path.join(argPath, filename)
file_stat = os.lstat(filepath)
mode = file_stat.st_mode
filename += "/" if stat.S_ISDIR(mode) else ""
nlink = file_stat.st_nlink
username = pwd.getpwuid(file_stat.st_uid).pw_name
group = grp.getgrgid(file_stat.st_gid).gr_name
fsize = file_stat.st_size
access = convertAccess(mode)
ctime = time.strftime("%b %d %H:%M", time.localtime(file_stat.st_ctime))
output += "%s %d %s %s %d %s %s\n" % (access, nlink, username, group, fsize, ctime, filename)
return output
def convertAccess(mode):
access = ["-"] * 10
if stat.S_ISDIR(mode):
access[0] = "d"
elif stat.S_ISLNK(mode):
access[0] = "l"
if stat.S_IRUSR & mode:
access[1] = "r"
if stat.S_IWUSR & mode:
access[2] = "w"
if stat.S_IXUSR & mode:
access[3] = "x"
if stat.S_IRGRP & mode:
access[4] = "r"
if stat.S_IWGRP & mode:
access[5] = "w"
if stat.S_IXGRP & mode:
access[6] = "x"
if stat.S_IROTH & mode:
access[7] = "r"
if stat.S_IWOTH & mode:
access[8] = "w"
if stat.S_IXOTH & mode:
access[9] = "x"
return "".join(access)
if __name__ == '__main__':
ls()