Skip to content

Commit aee68b7

Browse files
committed
implementation of cat with python
1 parent 60d6701 commit aee68b7

2 files changed

Lines changed: 54 additions & 4 deletions

File tree

implement-shell-tools/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.venv/

implement-shell-tools/cat/mycat.py

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,64 @@ def expand_paths(paths):
1313
files.extend(matches)
1414
else:
1515
files.append(p) # keep as-is (will error later if missing)
16-
return sorted(files)
16+
return sorted(files)
1717

1818
def read_lines(file):
1919
with open(file, "r", encoding="utf-8") as f:
2020
return f.readlines()
2121

22-
def print_lines(files, number_lines==False, number_nonempty=False):
22+
def print_lines(files, number_all=False, number_nonempty=False):
2323
line_no = 1
2424
for file in files:
25-
25+
try:
26+
lines = read_lines(file)
27+
except FileNotFoundError:
28+
print(f"cat: {file}: No such file or directory", file=sys.stderr)
29+
continue
2630

27-
31+
for line in lines:
32+
is_empty = (line.strip() == "")
33+
34+
if number_nonempty:
35+
if not is_empty:
36+
prefix = f"{line_no:6}\t"
37+
line_no += 1
38+
else:
39+
prefix = ""
40+
elif number_all:
41+
prefix = f"{line_no:6}\t"
42+
line_no += 1
43+
else:
44+
prefix = ""
45+
46+
# avoid double newlines: line already includes '\n'
47+
sys.stdout.write(prefix + line)
48+
49+
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+
74+
if __name__ == "__main__":
75+
main()
76+

0 commit comments

Comments
 (0)