Skip to content

Commit 0591f3f

Browse files
committed
handle errors when reading file
1 parent 38c96e9 commit 0591f3f

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

  • implement-shell-tools/cat

‎implement-shell-tools/cat/cat.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
import sys
23

34
parser = argparse.ArgumentParser(
45
prog="a simple cat implementation",
@@ -11,4 +12,25 @@
1112

1213
args = parser.parse_args();
1314

14-
print(args)
15+
# cat returns different error messages depending on the reason the path could be read
16+
def cat_file(path):
17+
try:
18+
with open(path, "r",) as f:
19+
content = f.read()
20+
except FileNotFoundError:
21+
print(f"cat: {path}: No such file or directory", file=sys.stderr)
22+
return
23+
except IsADirectoryError:
24+
print(f"cat: {path}: Is a directory", file=sys.stderr)
25+
return
26+
except PermissionError:
27+
print(f"cat: {path}: Permission denied", file=sys.stderr)
28+
return
29+
30+
print(content)
31+
32+
33+
34+
for path in args.paths:
35+
line_num = 1
36+
cat_file(path)

0 commit comments

Comments
 (0)