import argparse
def validate_options(args):
"""Validates command-line arguments."""
# Check if required argument 'input_file' is provided
if not args.input_file:
raise argparse.ArgumentError("input_file must be specified")
# Check if 'output_file' is provided, but not the same as input
if args.output_file and args.output_file == args.input_file:
raise argparse.ArgumentError("output_file must be different from input_file")
# Check if 'mode' is one of the allowed values
allowed_modes = ["read", "write", "append"]
if args.mode not in allowed_modes:
raise argparse.ArgumentError(f"mode must be one of: {', '.join(allowed_modes)}")
# Check if 'verbose' is a boolean
if not isinstance(args.verbose, bool):
raise argparse.ArgumentError("'verbose' must be a boolean") # Handle potential type errors
return args #Return the validated arguments
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Simple data processing tool.")
parser.add_argument("input_file", help="Path to the input file")
parser.add_argument("-o", "--output_file", help="Path to the output file (optional)")
parser.add_argument("-m", "--mode", choices=["read", "write", "append"], help="Operation mode")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
args = parser.parse_args()
try:
validated_args = validate_options(args)
# Proceed with the data processing using the validated arguments
print("Arguments are valid.")
print(f"Input file: {validated_args.input_file}")
if validated_args.output_file:
print(f"Output file: {validated_args.output_file}")
print(f"Mode: {validated_args.mode}")
print(f"Verbose: {validated_args.verbose}")
except argparse.ArgumentError as e:
print(f"Error: {e}")
Add your comment