当使用Python的optparse模块为选项生成帮助时,可以使用%defualt占位符将该选项的默认值插入到帮助中。当类型是选择时,是否对有效的选择做同样的事情?
例如类似于:
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")发布于 2014-04-03 14:17:21
我想你的问题是你不想重复选择的清单。幸运的是,对于这类问题,变量是普遍的,即使有时是丑陋的解决方案。所以,丑陋但务实的答案是:
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解析来完成。
发布于 2014-04-03 14:14:58
正如@msvalkon评论的那样,optparse被废弃了--使用argparse解析代替。
可以在%(choices)s参数中指定help占位符:
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()下面是控制台上的内容:
$ 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发布于 2014-04-03 14:20:49
argparse解析默认打印选项,如下面的演示所示。自动打印默认值的一种方法是使用ArgumentsDefaultHelpFormatter。
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-m","--method", type=str, choices=("method1","method2","method3"),
default="method1", help = "Method to use.")
parser.parse_args()演示:
msvalkon@Lunkwill:/tmp$ python test.py -h
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. (default: method1)https://stackoverflow.com/questions/22840202
复制相似问题