Shark
Shark

Reputation: 2382

Display list of option choices in help text automatically in OptionParser

I have an option in OptionParser that takes in a list of choices.

#!/usr/bin/python

from optparse import OptionParser

def main():
    parser = OptionParser(usage="Usage: foo")  
    parser.add_option('-e', '--env',
                  type='choice',
                  action='store',
                  dest='environment',
                  choices=['prod', 'staging', 'test', 'dev'],
                  default='dev',
                  help='Environment to run on',)


if __name__ == '__main__':
    main()

When I run --help command, I see:

Usage: foo

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -e ENVIRONMENT, --env=ENVIRONMENT
                        Environment to run on

I'd like it so that my list of choices automatically shows up in environment's help text (and preferably even the default). Is there any way to access the choices object to be used to generate the help text?

Upvotes: 0

Views: 347

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122154

One simple way would be something like:

choices = ['prod', 'staging', 'test', 'dev'] 
help = "Environment to run on (choose from: {!r})".format(choices)
parser.add_option('-e', '--env',
                  type='choice',
                  action='store',
                  dest='environment',
                  choices=choices,
                  default='dev',
                  help=help,)

which produces:

Usage: foo

Options:
  -h, --help            show this help message and exit
  -e ENVIRONMENT, --env=ENVIRONMENT
                        Environment to run on (choose from: ['prod',
                        'staging', 'test', 'dev'])

You could put a bit more effort into the help assignment if you want the help to look neater!

Upvotes: 2

9000
9000

Reputation: 40904

You can put %default into the help text and it will be expanded to the default value of that option (see docs).

With choices, I'm afraid, you have to put them into a separate list and add manually. It allows to add explanations, though:

env_choices = [
  ('prod', 'production; use caution!'),
  ('test', 'used by testers, do not break')
  ('dev', 'developers\' safe playgroud')
]

# ...
choices = [name for name, _ in env_choices],
help = "Environment (defaults to %default); one of:\n %s" % (
         "\n\t".join(name + ": " + descr for name, descr in env_choices)  
       )

Upvotes: 2

Related Questions