Python argparse:在用法信息中单独列出位置参数的可选选项
这事儿用Python的argparse模块就能轻松搞定,核心是通过自定义帮助文本和格式器来实现你想要的帮助输出效果。我给你写个完整的示例代码,再拆解下关键细节:
import argparse # 先把可选配料和对应的描述存成字典,方便后续复用 INGREDIENT_OPTIONS = { 'bacon': 'Lovely bacon', 'egg': 'The runny kind', 'sausage': 'Just a roll', 'spam': 'Glorious SPAM', 'tomato': 'Sliced and diced' } # 创建参数解析器,指定RawTextHelpFormatter来保留帮助文本里的换行和格式 parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter ) # 添加位置参数:支持多个配料,限制只能选字典里的选项,同时自定义帮助文本 parser.add_argument( 'INGREDIENT', nargs='+', choices=INGREDIENT_OPTIONS.keys(), help=f"your choice of ingredients:\n{''.join(f' {ing:<10} {desc}\n' for ing, desc in INGREDIENT_OPTIONS.items())}" ) # 添加--customer可选参数 parser.add_argument('--customer', help='Specify the customer name') # 解析命令行参数(这里之后可以加你的业务逻辑) args = parser.parse_args() # 示例业务逻辑:打印订单信息 if args.customer: print(f"Making breakfast for {args.customer}:") print(f"Selected ingredients: {', '.join(args.INGREDIENT)}")
关键细节说明:
RawTextHelpFormatter:这个格式器会保留你在帮助文本里写的换行和空格,避免默认格式把所有内容挤成一行,这样配料列表才能整齐显示。- 位置参数的
choices:既限制了用户只能输入指定的配料,又能让argparse自动校验参数合法性。 - 自定义帮助文本:通过字符串拼接把配料字典里的键值对转换成整齐的列表,直接嵌入到位置参数的
help字段里。
你运行python breakfast.py --help后,就能得到和你需求完全一致的输出:
usage: breakfast.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...] positional arguments: INGREDIENT your choice of ingredients: bacon Lovely bacon egg The runny kind sausage Just a roll spam Glorious SPAM tomato Sliced and diced optional arguments: -h, --help show this help message and exit --customer CUSTOMER Specify the customer name
内容的提问来源于stack exchange,提问作者MacFreek
相关产品推荐
相关产品推荐

