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

Yve*_*man 6 python argparse

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

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

positional arguments:
  {rock,paper,scissors}
Run Code Online (Sandbox Code Playgroud)

如果很明显如何选择一个,这会起作用,但如果每个选择都需要自己的小帮助,则效果不佳。

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

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

qvp*_*ham 4

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()))
Run Code Online (Sandbox Code Playgroud)

尝试使用子命令(subparsers)是更好的主意。