You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 days or thread are valid integers, and prompts the user to correct mistakes.
  • Familiar output: The args object works exactly like it did with parse_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:37:44