Skip to content

Commit 7b4197c

Browse files
committed
Implement cat shell tool in Python
1 parent b5089a2 commit 7b4197c

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

  • implement-shell-tools/implement-shell-tools-python/cat
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env python3
2+
import sys
3+
import os
4+
5+
global_line_counter = 1
6+
7+
def print_file(file_path, options):
8+
global global_line_counter
9+
try:
10+
with open(file_path, "r", encoding="utf-8") as f:
11+
content = f.read()
12+
13+
lines = content.split("\n")
14+
if lines and lines[-1] == "":
15+
lines.pop()
16+
17+
for line in lines:
18+
prefix = ""
19+
20+
should_number = (
21+
options["number_mode"] == "all" or
22+
(options["number_mode"] == "non-empty" and line.strip() != "")
23+
)
24+
25+
if should_number:
26+
prefix = f"{global_line_counter:6}\t"
27+
global_line_counter += 1
28+
29+
sys.stdout.write(prefix + line + "\n")
30+
31+
except Exception as e:
32+
print(f"cat: {file_path}: {e}", file=sys.stderr)
33+
sys.exit(1)
34+
35+
36+
def main():
37+
global global_line_counter
38+
args = sys.argv[1:]
39+
40+
options = {"number_mode": "off"}
41+
files = []
42+
43+
for arg in args:
44+
if arg == "-n":
45+
options["number_mode"] = "all"
46+
elif arg == "-b":
47+
options["number_mode"] = "non-empty"
48+
else:
49+
files.append(arg)
50+
51+
if not files:
52+
print("cat: missing file operand", file=sys.stderr)
53+
sys.exit(1)
54+
55+
for file_path in files:
56+
global_line_counter = 1
57+
print_file(file_path, options)
58+
59+
60+
if __name__ == "__main__":
61+
main()

0 commit comments

Comments
 (0)