Python 列出OptPass帮助输出中的选项

Python 列出OptPass帮助输出中的选项,python,Python,使用Python的optparse模块为选项生成帮助时,可以使用%defualt占位符将选项的默认值插入帮助中。当类型为choice时,是否有必要对有效的选项执行相同的操作 例如: import optparse parser=optparse.OptionParser() parser.add_option("-m","--method", type = "choice", choices = ("method1","method2","method3"),

使用Python的optparse模块为选项生成帮助时,可以使用
%defualt
占位符将选项的默认值插入帮助中。当类型为choice时,是否有必要对有效的选项执行相同的操作

例如:

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")

正如@msvalkon评论的那样,
optparse
已被弃用-请改用

您可以在
帮助
参数中指定
%(选项)s
占位符:

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

我想你的问题是你不想重复选择的清单。幸运的是,对于这类问题,变量是通用的,即使有时是难看的解决方案。因此,丑陋但务实的答案是:

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)
当然,这种事情也可以使用argparse来完成。

默认情况下打印选项,如下面的演示所示。自动打印默认值的一种方法是使用

演示:

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)

Optparse被认为已弃用。您应该使用。@msvalkon:您有使用argparse解决此问题的方法吗?@JohnZwinck我们开始了,毕竟添加了一个。不幸的是,我在一个使用optparse的框架内工作,在上游使用之前,我没有切换到使用argparse的选项。可能会添加
default='method\u n'
?问题是确保将来对有效选项列表的任何更改都会自动反映在帮助消息中。只要未来的维护人员了解正在发生的事情,这种方法就应该有效。
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)