1. import argparse
  2. import sys
  3. def deduplicate_cli_args(parser, args_list, max_retries=3):
  4. """
  5. Deduplicates CLI arguments from a list, handling potential errors with retry logic.
  6. Args:
  7. parser: The argparse.ArgumentParser object.
  8. args_list: A list of strings representing the CLI arguments.
  9. max_retries: The maximum number of retries if an error occurs during deduplication.
  10. Returns:
  11. A dictionary where keys are argument names and values are the corresponding values.
  12. Returns None if the operation fails after max_retries attempts.
  13. """
  14. retries = 0
  15. while retries < max_retries:
  16. try:
  17. args = parser.parse_args(args_list)
  18. return vars(args)
  19. except Exception as e:
  20. retries += 1
  21. if retries < max_retries:
  22. print(f"Deduplication failed (attempt {retries}/{max_retries}): {e}", file=sys.stderr)
  23. # Optionally add a delay before retrying
  24. # import time
  25. # time.sleep(0.1)
  26. else:
  27. print(f"Deduplication failed after {max_retries} attempts: {e}", file=sys.stderr)
  28. return None
  29. if __name__ == '__main__':
  30. parser = argparse.ArgumentParser()
  31. parser.add_argument("--a", type=str, help="Argument a")
  32. parser.add_argument("--b", type=str, help="Argument b")
  33. parser.add_argument("--a", type=str, help="Duplicate argument a") #intentional duplicate
  34. args_to_deduplicate = ["--a", "value1", "--b", "value2", "--a", "value3"]
  35. deduplicated_args = deduplicate_cli_args(parser, args_to_deduplicate)
  36. if deduplicated_args:
  37. print("Deduplicated arguments:")
  38. print(deduplicated_args)
  39. else:
  40. print("Deduplication failed.")

Add your comment