Skip to content

Commit 95f3415

Browse files
committed
task(cat): convert JS code to python
1 parent 949f78b commit 95f3415

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import argparse
2+
import sys
3+
4+
5+
def parse_args():
6+
parser = argparse.ArgumentParser(
7+
description="Reads file(s) and writes them to the standard output",
8+
)
9+
parser.add_argument("paths", nargs="+", help="The file path(s) to process")
10+
parser.add_argument(
11+
"-n",
12+
action="store_true",
13+
dest="number_all",
14+
help="Number the output lines, starting at 1.",
15+
)
16+
parser.add_argument(
17+
"-b",
18+
action="store_true",
19+
dest="number_nonblank",
20+
help="Number only non-blank output lines, starting at 1.",
21+
)
22+
return parser.parse_args()
23+
24+
25+
def main():
26+
args = parse_args()
27+
28+
try:
29+
for path in args.paths:
30+
line_num = 1
31+
32+
with open(path, "r", encoding="utf-8") as file:
33+
for raw_line in file:
34+
line = raw_line.rstrip("\n")
35+
is_blank = line.strip() == ""
36+
should_number = args.number_all or (
37+
args.number_nonblank and not is_blank)
38+
39+
if should_number:
40+
print(f"{line_num} {line}")
41+
line_num += 1
42+
else:
43+
print(line)
44+
except OSError as err:
45+
print(err, file=sys.stderr)
46+
47+
return 0
48+
49+
50+
main()

0 commit comments

Comments
 (0)