Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to write a one-line help per choice for argparse choices?

With python argaparse "choices" the default help looks like this:

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

positional arguments:
  {rock,paper,scissors}

Which works if it's obvious how to pick one, but not so great if each choice needs its own mini-help.

Is there any way to write one line help per choice in a clean way, something along these lines:

parser.add_argument("action",
                    choices=[
                        ["status", help="Shows current status of sys"],
                        ["load", help="Load data in DB"],
                        ["dump", help="Dump data to csv"],
                    ],
like image 826
Yves Dorfsman Avatar asked May 07 '16 22:05

Yves Dorfsman


1 Answers

argparse doesn't support this format. Here is my solution. It isn't nice, but it works.

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()))

Try to use Sub-commands(subparsers) is the better idea.

like image 168
qvpham Avatar answered Nov 14 '22 23:11

qvpham