|
| 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() |
0 commit comments