Skip to content

Commit ad6883f

Browse files
committed
corrected error handling issue and moved the main up.
1 parent efadbb0 commit ad6883f

1 file changed

Lines changed: 30 additions & 19 deletions

File tree

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

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,7 @@
33
import sys
44
import os
55

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('.')])
226

23-
for entry in entries:
24-
print(entry)
257

268
def main():
279
args = sys.argv[1:]
@@ -41,8 +23,37 @@ def main():
4123
if not paths:
4224
paths = ["."]
4325

26+
had_error = False
27+
4428
for path in paths:
45-
list_dir(path, show_all, one_per_line)
29+
if list_dir(path, show_all, one_per_line):
30+
had_error = True
31+
32+
if had_error:
33+
sys.exit(1)
34+
35+
36+
def list_dir(path, show_all=False, one_per_line = False):
37+
try:
38+
entries = os.listdir(path)
39+
except FileNotFoundError:
40+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
41+
return True
42+
43+
entries = sorted(entries)
44+
45+
if show_all:
46+
normal = sorted([e for e in entries if not e.startswith('.')])
47+
hidden = sorted([e for e in entries if e.startswith('.')])
48+
49+
entries = [".", ".."] + normal + hidden
50+
else:
51+
entries = sorted([e for e in entries if not e.startswith('.')])
52+
53+
for entry in entries:
54+
print(entry)
55+
56+
4657

4758
if __name__ == "__main__":
4859
main()

0 commit comments

Comments
 (0)