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")
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With