Python to Implementation of Cat Command For Beginners

Cat command implementation using python.

Run:

On Linux, you can use 

./cat.py [path]

OR

python ./cat.py [path]

Example:

./cat.py ./test_cat.txt

Source Code:

cat.py

#!/usr/bin/python import argparse from pathlib import Path from sys import stderr, stdout import os class CatError(Exception): pass class Logger: def __init__(self, verbosity=False): self.verbose = verbosity def error(self, message): print(f'ERROR: {message}') logger = Logger() ''' Read the selected text file Example: your/path/file.txt ''' def readFile(src: Path): ''' if the given path is a directory ERROR the path is a directory ''' if src.is_dir(): logger.error(f'The path {src}: is a directory') else: with open(src, 'r') as f: for lines in f: print(lines, end='') def cli() -> argparse.Namespace: parser = argparse.ArgumentParser( prog='cat', description='cat command implementation in python', epilog='Example: your/path/file.txt' ) parser.add_argument( 'source', type=Path, help='Source file' ) return parser.parse_args() def main(): args = cli() try: readFile(args.source) except CatError as e: logger.error(e) exit(1) except KeyboardInterrupt: logger.error('\nInterrupt') ''' Start the program ''' if __name__ == '__main__': main()

test_cat.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam consequat elit vel pretium pellentesque. Vivamus commodo leo sed lorem auctor elementum. Maecenas ut erat ut velit maximus luctus. Vestibulum varius justo et mauris tristique pharetra rutrum porta nulla. Nam porttitor lobortis posuere. Aenean erat nisl, aliquam id molestie in, luctus quis mauris. Donec fermentum vel quam in consectetur. Aliquam nec mauris quis tellus faucibus fermentum. Suspendisse ac maximus sem. Fusce feugiat non dui non gravida. Ut ac eleifend tellus. Vivamus consectetur finibus nisi. Etiam id odio vitae arcu aliquam tincidunt nec sit amet quam.

Leave a Comment