在 OptionParser 中自动显示帮助文本中的选项列表

Display list of option choices in help text automatically in OptionParser

我在 OptionParser 中有一个选项,它包含一个选项列表。

#!/usr/bin/python

from optparse import OptionParser

def main():
    parser = OptionParser(usage="Usage: foo")  
    parser.add_option('-e', '--env',
                  type='choice',
                  action='store',
                  dest='environment',
                  choices=['prod', 'staging', 'test', 'dev'],
                  default='dev',
                  help='Environment to run on',)


if __name__ == '__main__':
    main()

当我 运行 --help 命令时,我看到:

Usage: foo

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -e ENVIRONMENT, --env=ENVIRONMENT
                        Environment to run on

我希望这样我的选择列表会自动显示在环境的帮助文本中(最好是默认值)。有什么方法可以访问用于生成帮助文本的 choices 对象?

一个简单的方法是这样的:

choices = ['prod', 'staging', 'test', 'dev'] 
help = "Environment to run on (choose from: {!r})".format(choices)
parser.add_option('-e', '--env',
                  type='choice',
                  action='store',
                  dest='environment',
                  choices=choices,
                  default='dev',
                  help=help,)

产生:

Usage: foo

Options:
  -h, --help            show this help message and exit
  -e ENVIRONMENT, --env=ENVIRONMENT
                        Environment to run on (choose from: ['prod',
                        'staging', 'test', 'dev'])

如果您想让帮助看起来更整洁,您可以在 help 作业中多花点功夫!

您可以将 %default 放入帮助文本中,它将扩展为该选项的默认值 (see docs)。

有了选择,恐怕您必须将它们放入单独的列表中并手动添加。不过,它允许添加解释:

env_choices = [
  ('prod', 'production; use caution!'),
  ('test', 'used by testers, do not break')
  ('dev', 'developers\' safe playgroud')
]

# ...
choices = [name for name, _ in env_choices],
help = "Environment (defaults to %default); one of:\n %s" % (
         "\n\t".join(name + ": " + descr for name, descr in env_choices)  
       )