cat.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/python
  2. import argparse
  3. from pathlib import Path
  4. from sys import stderr, stdout
  5. import os
  6. class CatError(Exception):
  7. pass
  8. class Logger:
  9. def __init__(self, verbosity=False):
  10. self.verbose = verbosity
  11. def error(self, message):
  12. print(f'ERROR: {message}')
  13. logger = Logger()
  14. '''
  15. Read the selected text file
  16. Example:
  17. your/path/file.txt
  18. '''
  19. def readFile(src: Path):
  20. '''
  21. if the given path is a directory
  22. ERROR the path is a directory
  23. '''
  24. if src.is_dir():
  25. logger.error(f'The path {src}: is a directory')
  26. else:
  27. with open(src, 'r') as f:
  28. for lines in f:
  29. print(lines, end='')
  30. def cli() -> argparse.Namespace:
  31. parser = argparse.ArgumentParser(
  32. prog='cat',
  33. description='cat command implementation in python',
  34. epilog='Example: your/path/file.txt'
  35. )
  36. parser.add_argument(
  37. 'source',
  38. type=Path,
  39. help='Source file'
  40. )
  41. return parser.parse_args()
  42. def main():
  43. args = cli()
  44. try:
  45. readFile(args.source)
  46. except CatError as e:
  47. logger.error(e)
  48. exit(1)
  49. except KeyboardInterrupt:
  50. logger.error('\nInterrupt')
  51. '''
  52. Start the program
  53. '''
  54. if __name__ == '__main__':
  55. main()