import argparse
import sys
def restore_cli_args(args):
"""Restores CLI arguments from a dictionary, with defensive checks."""
# Create a new parser with the same arguments as the original.
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
# Add the arguments from the dictionary.
for name, value in args.items():
if isinstance(value, str):
parser.add_argument(name, type=str, help=value) # Default to string type
elif isinstance(value, int):
parser.add_argument(name, type=int, help=str(value)) # Convert int to string for help
elif isinstance(value, float):
parser.add_argument(name, type=float, help=str(value))# Convert float to string for help
elif isinstance(value, bool):
parser.add_argument(name, action='store_true' if value else 'store_false', help=str(value))
else:
print(f"Warning: Unsupported type for argument '{name}'. Skipping.")
continue # Skip unsupported types
# Parse the arguments.
try:
restored_args = parser.parse_args()
return vars(restored_args) # Return dictionary of arguments
except SystemExit:
print("Error restoring arguments. Check the argument values.")
return None # Indicate failure
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
if __name__ == '__main__':
# Example usage:
# Define the arguments to restore
cli_args = {
'input_file': 'data.txt',
'output_dir': 'output',
'verbose': True,
'threshold': 0.5
}
# Restore the CLI arguments
restored_args = restore_cli_args(cli_args)
if restored_args:
print("CLI arguments restored:")
print(restored_args)
Add your comment