如何将Argparse命令行接口改为逐个交互式输入参数
Convert Argparse CLI to Prompt for Parameters One by One
Hey there! I get that you want to switch from passing all arguments at once to prompting users for each value individually. Here's a clean way to adjust your code while keeping the benefits of argparse (like type validation and help text reuse):
Solution with Input Validation
This approach retains your original argparse setup so you can leverage its built-in type checking and help messages for prompts:
import argparse my_parser = argparse.ArgumentParser(fromfile_prefix_chars='@') my_parser.add_argument('id', help='Enter id') my_parser.add_argument('url', help='Enter url') my_parser.add_argument('days', help='Enter days', type=int) # Define integer type my_parser.add_argument('param', help='Enter param') my_parser.add_argument('code', help='Enter code') my_parser.add_argument('thread', help='Enter thread', type=int) # Define integer type my_parser.add_argument('file', help='Enter file') # Collect parameters via prompts args_dict = {} for action in my_parser._actions: # Skip default help/version actions if action.dest in ['help', 'version']: continue prompt_text = action.help + ': ' while True: user_input = input(prompt_text) # Handle type conversion and validation if action.type is not None: try: user_input = action.type(user_input) break except ValueError: print(f"Oops! That's not a valid {action.type.__name__}. Please try again.") else: break args_dict[action.dest] = user_input # Convert to the same Namespace object you used before args = argparse.Namespace(**args_dict) # You can use args just like you did before! print(f"ID: {args.id}, Days: {args.days}, Threads: {args.thread}")
Key Features:
- Reuses your existing argparse setup: No need to redefine parameter descriptions or types.
- Type validation: Automatically checks if inputs like
daysorthreadare valid integers, and prompts the user to correct mistakes. - Familiar output: The
argsobject works exactly like it did withparse_args(), so you don't have to change any downstream code.
Simplified Version (No Validation)
If you don't need strict type checking, you can skip the argparse loop and directly prompt for each value:
import argparse # Create an empty Namespace to mimic the original args object args = argparse.Namespace() args.id = input('Enter id: ') args.url = input('Enter url: ') args.days = input('Enter days: ') args.param = input('Enter param: ') args.code = input('Enter code: ') args.thread = input('Enter thread: ') args.file = input('Enter file: ') # Use your args variables as usual print(args.file)
This is quicker to implement if you don't need input validation, and still gives you the same args structure you're used to.
内容的提问来源于stack exchange,提问作者ram p
相关产品推荐
相关产品推荐

