在optparse帮助输出中列出选项

3 投票
3 回答
2858 浏览
提问于 2025-04-18 01:10

当你使用Python的optparse模块生成选项的帮助信息时,可以用%default这个占位符来插入该选项的默认值到帮助信息中。那么,对于类型是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")

3 个回答

1

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

正如@msvalkon所说,optparse已经不再推荐使用了,建议使用argparse

你可以在help参数中指定%(choices)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
3

我猜你遇到的问题是你不想重复列出所有的选择。幸运的是,使用变量是解决这类问题的一种通用方法,虽然有时候看起来不太美观。所以,虽然有点丑但实用的解决办法是:

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来实现。

撰写回答