1. import argparse
  2. import sys
  3. def restore_cli_args(args):
  4. """Restores CLI arguments from a dictionary, with defensive checks."""
  5. # Create a new parser with the same arguments as the original.
  6. parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
  7. # Add the arguments from the dictionary.
  8. for name, value in args.items():
  9. if isinstance(value, str):
  10. parser.add_argument(name, type=str, help=value) # Default to string type
  11. elif isinstance(value, int):
  12. parser.add_argument(name, type=int, help=str(value)) # Convert int to string for help
  13. elif isinstance(value, float):
  14. parser.add_argument(name, type=float, help=str(value))# Convert float to string for help
  15. elif isinstance(value, bool):
  16. parser.add_argument(name, action='store_true' if value else 'store_false', help=str(value))
  17. else:
  18. print(f"Warning: Unsupported type for argument '{name}'. Skipping.")
  19. continue # Skip unsupported types
  20. # Parse the arguments.
  21. try:
  22. restored_args = parser.parse_args()
  23. return vars(restored_args) # Return dictionary of arguments
  24. except SystemExit:
  25. print("Error restoring arguments. Check the argument values.")
  26. return None # Indicate failure
  27. except Exception as e:
  28. print(f"An unexpected error occurred: {e}")
  29. return None
  30. if __name__ == '__main__':
  31. # Example usage:
  32. # Define the arguments to restore
  33. cli_args = {
  34. 'input_file': 'data.txt',
  35. 'output_dir': 'output',
  36. 'verbose': True,
  37. 'threshold': 0.5
  38. }
  39. # Restore the CLI arguments
  40. restored_args = restore_cli_args(cli_args)
  41. if restored_args:
  42. print("CLI arguments restored:")
  43. print(restored_args)

Add your comment