1. import argparse
  2. def validate_options(args):
  3. """Validates command-line arguments."""
  4. # Check if required argument 'input_file' is provided
  5. if not args.input_file:
  6. raise argparse.ArgumentError("input_file must be specified")
  7. # Check if 'output_file' is provided, but not the same as input
  8. if args.output_file and args.output_file == args.input_file:
  9. raise argparse.ArgumentError("output_file must be different from input_file")
  10. # Check if 'mode' is one of the allowed values
  11. allowed_modes = ["read", "write", "append"]
  12. if args.mode not in allowed_modes:
  13. raise argparse.ArgumentError(f"mode must be one of: {', '.join(allowed_modes)}")
  14. # Check if 'verbose' is a boolean
  15. if not isinstance(args.verbose, bool):
  16. raise argparse.ArgumentError("'verbose' must be a boolean") # Handle potential type errors
  17. return args #Return the validated arguments
  18. if __name__ == '__main__':
  19. parser = argparse.ArgumentParser(description="Simple data processing tool.")
  20. parser.add_argument("input_file", help="Path to the input file")
  21. parser.add_argument("-o", "--output_file", help="Path to the output file (optional)")
  22. parser.add_argument("-m", "--mode", choices=["read", "write", "append"], help="Operation mode")
  23. parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
  24. args = parser.parse_args()
  25. try:
  26. validated_args = validate_options(args)
  27. # Proceed with the data processing using the validated arguments
  28. print("Arguments are valid.")
  29. print(f"Input file: {validated_args.input_file}")
  30. if validated_args.output_file:
  31. print(f"Output file: {validated_args.output_file}")
  32. print(f"Mode: {validated_args.mode}")
  33. print(f"Verbose: {validated_args.verbose}")
  34. except argparse.ArgumentError as e:
  35. print(f"Error: {e}")

Add your comment