>> parser.add_argument('move', choices=['rock', 'paper', 'sc-6ren">
gpt4 book ai didi

python - 有没有一种干净的方法可以为 argparse 选择的每个选择编写一行帮助?

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:35 25 4
gpt4 key购买 nike

使用 python argaparse "choices"默认帮助如下所示:

>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])

positional arguments:
{rock,paper,scissors}

如果很明显如何选择一个,那么这很有效,但如果每个选择都需要自己的迷你帮助,那就不太好了。

有没有办法以干净的方式为每个选择编写一行帮助,大致如下:

parser.add_argument("action",
choices=[
["status", help="Shows current status of sys"],
["load", help="Load data in DB"],
["dump", help="Dump data to csv"],
],

最佳答案

argparse 不支持这种格式。这是我的解决方案。这不是很好,但它确实有效。

from argparse import ArgumentParser, RawTextHelpFormatter

choices_helper = { "status": "Shows current status of sys",
"load": "Load data in DB",
"dump": "Dump data to csv"}

parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)
parser.add_argument("action",
choices=choices_helper,
help='\n'.join("{}: {}".format(key, value) for key, value in choices_helper.iteritems()))

尝试使用 Sub-commands(subparsers)是更好的主意。

关于python - 有没有一种干净的方法可以为 argparse 选择的每个选择编写一行帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com