Search code examples
pythonoptionparser

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?


Solution

  • 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!