Skip to content

Commit 80ca854

Browse files
committed
implementation of ls with python
1 parent aee68b7 commit 80ca854

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

implement-shell-tools/cat/mycat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import sys
44
import glob
5-
import os
5+
66

77
def expand_paths(paths):
88
"""Expand glob patterns and return sorted unique file list."""

implement-shell-tools/ls/my-ls.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python3
2+
3+
import sys
4+
import os
5+
6+
def list_dir(path, show_all=False, one_per_line = False):
7+
try:
8+
entries = os.listdir(path)
9+
except FileNotFoundError:
10+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
11+
return
12+
13+
entries = sorted(entries)
14+
15+
if show_all:
16+
normal = sorted([e for e in entries if not e.startswith('.')])
17+
hidden = sorted([e for e in entries if e.startswith('.')])
18+
19+
entries = [".", ".."] + normal + hidden
20+
else:
21+
entries = sorted([e for e in entries if not e.startswith('.')])
22+
23+
for entry in entries:
24+
print(entry)
25+
26+
def main():
27+
args = sys.argv[1:]
28+
29+
show_all = False
30+
one_per_line = False
31+
paths = []
32+
33+
for a in args:
34+
if a == "-a":
35+
show_all = True
36+
elif a == "-1":
37+
one_per_line = True
38+
else:
39+
paths.append(a)
40+
41+
if not paths:
42+
paths = ["."]
43+
44+
for path in paths:
45+
list_dir(path, show_all, one_per_line)
46+
47+
if __name__ == "__main__":
48+
main()

0 commit comments

Comments
 (0)