1. import logging
  2. import traceback
  3. import argparse
  4. logging.basicConfig(level=logging.ERROR)
  5. def safe_file_operation(filepath, operation, *args, **kwargs):
  6. """
  7. Safely performs an operation on a file, wrapping errors and providing basic validation.
  8. """
  9. if not isinstance(filepath, str):
  10. raise TypeError("Filepath must be a string.")
  11. try:
  12. # Basic file existence check
  13. with open(filepath, 'r'): # Attempt to open to check if it exists
  14. pass # File exists, proceed
  15. except FileNotFoundError:
  16. raise FileNotFoundError(f"File not found: {filepath}")
  17. except Exception as e: #Catch other file access errors
  18. raise IOError(f"Error accessing file {filepath}: {e}")
  19. try:
  20. operation(filepath, *args, **kwargs)
  21. except Exception as e:
  22. logging.error(f"Error during operation on file {filepath}: {e}")
  23. print(f"An error occurred while processing {filepath}. See logs for details.")
  24. traceback.print_exc() #Print full traceback
  25. raise # Re-raise the exception to stop script execution if needed
  26. def main():
  27. parser = argparse.ArgumentParser(description="Safely perform file operations.")
  28. parser.add_argument("filepath", help="Path to the file.")
  29. parser.add_argument("operation", choices=['read', 'write', 'append'], help="Operation to perform.")
  30. parser.add_argument("-n", "--name", help="Name to write to file (for write/append).")
  31. args = parser.parse_args()
  32. if args.operation == 'read':
  33. safe_file_operation(args.filepath, open, mode='r')
  34. elif args.operation == 'write':
  35. if not args.name:
  36. parser.error("Name argument is required for write operation.")
  37. safe_file_operation(args.filepath, open, mode='w', write=args.name)
  38. elif args.operation == 'append':
  39. if not args.name:
  40. parser.error("Name argument is required for append operation.")
  41. safe_file_operation(args.filepath, open, mode='a', write=args.name)
  42. if __name__ == "__main__":
  43. main()

Add your comment