Skip to content

Commit 7f43d2a

Browse files
committed
implement ls command in python
1 parent d49d390 commit 7f43d2a

File tree

1 file changed

+49
-0
lines changed
  • implement-shell-tools/ls

1 file changed

+49
-0
lines changed

implement-shell-tools/ls/ls.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/env python3
2+
import sys
3+
import os
4+
5+
def list_dir(path=".", show_all=False):
6+
try:
7+
entries = os.listdir(path)
8+
if not show_all:
9+
entries = [e for e in entries if not e.startswith(".")]
10+
return sorted(entries)
11+
except FileNotFoundError:
12+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
13+
return []
14+
except NotADirectoryError:
15+
# If it's a file, just return it
16+
return [path]
17+
18+
def main():
19+
args = sys.argv[1:]
20+
21+
# Flags
22+
show_one_per_line = "-1" in args
23+
show_all = "-a" in args
24+
25+
# Remove flags from args
26+
paths = [arg for arg in args if arg not in ("-1", "-a")]
27+
28+
if not paths:
29+
paths = ["."] # default to current directory
30+
31+
for i, path in enumerate(paths):
32+
entries = list_dir(path, show_all=show_all)
33+
34+
if len(paths) > 1:
35+
print(f"{path}:")
36+
37+
for entry in entries:
38+
if show_one_per_line:
39+
print(entry)
40+
else:
41+
print(entry, end=" ")
42+
if not show_one_per_line:
43+
print() # newline after the row
44+
45+
if i < len(paths) - 1:
46+
print()
47+
48+
if __name__ == "__main__":
49+
main()

0 commit comments

Comments
 (0)