Skip to content

Commit bd591e3

Browse files
committed
ls command complete
1 parent d462b5a commit bd591e3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

implement-shell-tools/ls/my_ls.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import os
2+
import argparse
3+
4+
parser = argparse.ArgumentParser(
5+
prog="ls",
6+
description="List directory contents."
7+
)
8+
9+
parser.add_argument("-1", "--one-per-line", action="store_true", help="List one file per line")
10+
parser.add_argument("-a", "--all", action="store_true", help="Include hidden files (those starting with .)")
11+
parser.add_argument("paths", nargs="*", default=["."], help="Directory path(s) to list")
12+
13+
args = parser.parse_args()
14+
15+
for path in args.paths:
16+
try:
17+
entries = os.listdir(path)
18+
except Exception as e:
19+
print(f"ls: cannot access '{path}': {e}")
20+
continue
21+
22+
if not args.all:
23+
entries = [entry for entry in entries if not entry.startswith(".")]
24+
25+
entries.sort()
26+
27+
if args.one_per_line:
28+
for entry in entries:
29+
print(entry)
30+
else:
31+
print(" ".join(entries))

0 commit comments

Comments
 (0)