Skip to content

Commit efadbb0

Browse files
committed
error handling corrected, structure is changed, indentation fixed
1 parent ffb4416 commit efadbb0

1 file changed

Lines changed: 40 additions & 27 deletions

File tree

implement-shell-tools/cat/mycat.py

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,40 @@
33
import sys
44
import glob
55

6+
def main():
7+
args = sys.argv[1:]
8+
9+
if not args:
10+
print("Usage: cat [-n|-b] file...", file=sys.stderr)
11+
sys.exit(1)
12+
13+
number_all = False
14+
number_nonempty = False
15+
paths = []
16+
17+
for a in args:
18+
if a == "-n":
19+
number_all = True
20+
elif a == "-b":
21+
number_nonempty = True
22+
else:
23+
paths.append(a)
24+
25+
if number_nonempty:
26+
number_all = False
27+
28+
files = expand_paths(paths)
29+
30+
had_error = print_lines(
31+
files,
32+
number_all=number_all,
33+
number_nonempty=number_nonempty,
34+
)
35+
36+
if had_error:
37+
sys.exit(1)
638

39+
740
def expand_paths(paths):
841
"""Expand glob patterns and return sorted unique file list."""
942
files = []
@@ -16,16 +49,18 @@ def expand_paths(paths):
1649
return sorted(files)
1750

1851
def read_lines(file):
19-
with open(file, "r", encoding="utf-8") as f:
20-
return f.readlines()
52+
with open(file, "r", encoding="utf-8") as f:
53+
return f.readlines()
2154

2255
def print_lines(files, number_all=False, number_nonempty=False):
56+
had_error = False
2357
line_no = 1
2458
for file in files:
2559
try:
2660
lines = read_lines(file)
2761
except FileNotFoundError:
2862
print(f"cat: {file}: No such file or directory", file=sys.stderr)
63+
had_error = True
2964
continue
3065

3166
for line in lines:
@@ -46,31 +81,9 @@ def print_lines(files, number_all=False, number_nonempty=False):
4681
# avoid double newlines: line already includes '\n'
4782
sys.stdout.write(prefix + line)
4883

84+
return had_error
4985

50-
def main():
51-
args = sys.argv[1:]
52-
53-
if not args:
54-
print("Usage: cat [-n|-b] file...", file=sys.stderr)
55-
sys.exit(1)
56-
57-
number_all = False
58-
number_nonempty = False
59-
paths = []
60-
61-
for a in args:
62-
if a == "-n":
63-
number_all = True
64-
elif a == "-b":
65-
number_nonempty = True
66-
number_all = False #-b overrides -n
67-
else:
68-
paths.append(a)
69-
70-
files = expand_paths(paths)
71-
print_lines(files, number_all,number_nonempty)
72-
73-
7486
if __name__ == "__main__":
75-
main()
87+
main()
88+
7689

0 commit comments

Comments
 (0)