如何用argparse实现参数与自定义函数映射,仅运行指定参数对应函数?
How to Map argparse Arguments to Corresponding Custom Functions (Only Run Relevant Ones)
Hey there! I totally get what you're aiming for here—you want each command-line flag to trigger only its matching function, without running the others. The simplest and most scalable way to pull this off is using a dictionary to map your arguments directly to their respective functions. Let's refactor your code to make this work perfectly.
Complete Working Code
import argparse def func1(ip): print(f"Executing func1 with IP address: {ip}") # Replace with your actual logic here def func2(url): print(f"Executing func2 with URL: {url}") # Replace with your actual logic here def func3(action): print(f"Executing func3 with action: {action}") # Replace with your actual logic here if __name__ == "__main__": parser = argparse.ArgumentParser("Argument-Function Mapper") parser.add_argument("-u", "--url", help="Trigger func2 with a target URL") parser.add_argument("-i", "--ip", help="Trigger func1 with a target IP") parser.add_argument("-a", "--action", help="Trigger func3 with an action command") args = parser.parse_args() # Create a clear map of argument names to their associated functions arg_function_map = { "ip": func1, "url": func2, "action": func3 } # Loop through the map and run the function only if the argument was provided for arg_name, target_func in arg_function_map.items(): arg_value = getattr(args, arg_name) if arg_value is not None: target_func(arg_value)
Key Details Explained
- The Mapping Dictionary:
arg_function_mapcreates a direct link between each argument's internal name (the one you defined inadd_argument, like "ip" for--ip) and its function. This is way cleaner than writing a long chain ofif-elifstatements, and it's easy to update if you add more arguments later. - Check for Provided Arguments: We use
getattr(args, arg_name)to grab the value of each argument from the parsedargsobject. If the argument wasn't passed in the command line, its value will beNone—so we skip running that function entirely. - Optional: Enforce Single Argument Only
If you want to make sure users can only pass one flag at a time (e.g., no mixing-iand-u), add this check right after parsing arguments:# Count how many arguments have been provided provided_args_count = sum(1 for value in vars(args).values() if value is not None) if provided_args_count > 1: parser.error("Please use only one argument (-i, -u, or -a) per run.")
This approach keeps your code clean, maintainable, and exactly matches what you're asking for—only the function linked to the passed argument will run.
内容的提问来源于stack exchange,提问作者ioj
相关产品推荐
相关产品推荐

