Skip to content

Commit 38ad72c

Browse files
Merge pull request #1478 from DontEatThemCookies/master
Basic 'cat' program v1
2 parents 03a0391 + f1c1e8c commit 38ad72c

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

Cat/cat.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
The 'cat' Program Implemented in Python 3
3+
4+
The Unix 'cat' utility reads the contents
5+
of file(s) and 'conCATenates' into stdout.
6+
If it is run without any filename(s) given,
7+
then the program reads from standard input,
8+
which means it simply copies stdin to stdout.
9+
10+
It is fairly easy to implement such a program
11+
in Python, and as a result countless examples
12+
exist online. This particular implementation
13+
focuses on the basic functionality of the cat
14+
utility. Compatible with Python 3.6 or higher.
15+
16+
Syntax:
17+
python3 cat.py [filename1,filename2,etcetera]
18+
Separate filenames with commas and not spaces!
19+
20+
David Costell (DontEatThemCookies on GitHub)
21+
v1 - 02/06/2022
22+
"""
23+
import sys
24+
25+
def with_files(files):
26+
"""Executes when file(s) is/are specified."""
27+
file_contents = []
28+
try:
29+
# Read the files' contents and store their contents
30+
for file in files:
31+
with open(file) as f:
32+
file_contents.append(f.read())
33+
except OSError as err:
34+
# This executes when there's an error (e.g. FileNotFoundError)
35+
print(f"cat: error reading files ({err})")
36+
37+
# Write the contents of all files into the standard output stream
38+
for contents in file_contents:
39+
sys.stdout.write(contents)
40+
41+
def no_files():
42+
"""Executes when no file(s) is/are specified."""
43+
try:
44+
# Loop getting input then outputting the input.
45+
while True:
46+
inp = input()
47+
print(inp)
48+
# Gracefully handle Ctrl + C and Ctrl + D
49+
except KeyboardInterrupt:
50+
exit()
51+
except EOFError:
52+
exit()
53+
54+
def main():
55+
"""Entry point of the cat program."""
56+
try:
57+
# Read the arguments passed to the program
58+
with_files(sys.argv[1].strip().split(","))
59+
except IndexError:
60+
no_files()
61+
62+
if __name__ == "__main__":
63+
main()

Cat/text_a.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Sample Text Here
2+
3+
Lorem ipsum, dolor sit amet.
4+
Hello,
5+
World!
6+
7+
ABCD 1234

Cat/text_b.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
I am another sample text file.
2+
3+
The knights who say ni!
4+
5+
Lines
6+
of
7+
Text!

0 commit comments

Comments
 (0)