Skip to content

Commit d49d390

Browse files
committed
Implement cat command in Python
1 parent 407b010 commit d49d390

File tree

1 file changed

+48
-0
lines changed
  • implement-shell-tools/cat

1 file changed

+48
-0
lines changed

implement-shell-tools/cat/cat.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python3
2+
import sys
3+
import glob
4+
5+
def cat(files, number_all=False, number_nonblank=False):
6+
line_num = 1
7+
for filename in files:
8+
try:
9+
with open(filename, "r") as f:
10+
for line in f:
11+
stripped = line.rstrip("\n")
12+
13+
if number_all:
14+
print(f"{line_num:6}\t{stripped}")
15+
line_num += 1
16+
elif number_nonblank:
17+
if stripped:
18+
print(f"{line_num:6}\t{stripped}")
19+
line_num += 1
20+
else:
21+
print()
22+
else:
23+
print(stripped)
24+
except FileNotFoundError:
25+
print(f"cat: {filename}: No such file or directory", file=sys.stderr)
26+
27+
def main():
28+
args = sys.argv[1:]
29+
30+
number_all = "-n" in args
31+
number_nonblank = "-b" in args
32+
33+
# Remove flags from args
34+
files = [arg for arg in args if arg not in ("-n", "-b")]
35+
36+
# Expand globs like *.txt
37+
expanded_files = []
38+
for file in files:
39+
expanded_files.extend(glob.glob(file))
40+
41+
if not expanded_files:
42+
print("cat: missing file operand", file=sys.stderr)
43+
sys.exit(1)
44+
45+
cat(expanded_files, number_all=number_all, number_nonblank=number_nonblank)
46+
47+
if __name__ == "__main__":
48+
main()

0 commit comments

Comments
 (0)