Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing choices in optparse help output

Tags:

python

When you generate help for an option with Python's optparse module, you can use the %defualt placeholder to insert the default value for the option into the help. It there anyway of doing the same thing for the valid choices when the type is choice?

E.g something like:

import optparse
parser=optparse.OptionParser()
parser.add_option("-m","--method",
                  type = "choice", choices = ("method1","method2","method3"),
                  help = "Method to use. Valid choices are %choices. Default: %default")
like image 864
Ian Sudbery Avatar asked Sep 01 '25 20:09

Ian Sudbery


2 Answers

I assume your problem is that you don't want to repeat the list of choices. Fortunately variables are universal if sometimes ugly solution to this kind of problem. So the ugly-but-pragmatic answer is:

import optparse

choices_m = ("method1","method2","method3")
default_m = "method_1"

parser=optparse.OptionParser()
parser.add_option("-m","--method",
                  type = "choice", choices = choices_m, 
                  default = defult_m,
                  help = "Method to use. Valid choices are %s. Default: %s"\
                         % (choices_m, default_m)

And of course this kind of thing can be done using argparse too.

like image 197
Adrian Ratnapala Avatar answered Sep 07 '25 14:09

Adrian Ratnapala


As @msvalkon commented, optparse is deprecated - use argparse instead.

You can specify %(choices)s placeholder in the help argument:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument("-m",
                    "--method",
                    type=str,
                    choices=("method1", "method2", "method3"),
                    help = "Method to use. Valid choices are %(choices)s. Default: %(default)s",
                    default="method1")

parser.parse_args()

Here's what on the console:

$ python test.py --help
usage: test.py [-h] [-m {method1,method2,method3}]

optional arguments:
  -h, --help            show this help message and exit
  -m {method1,method2,method3}, --method {method1,method2,method3}
                        Method to use. Valid choices are method1, method2,
                        method3. Default: method1
like image 32
alecxe Avatar answered Sep 07 '25 14:09

alecxe