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

时间:2015-02-04 16:31:26

标签: python 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对象?

2 个答案:

答案 0 :(得分:2)

一种简单的方法是:

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作业中投入更多精力!

答案 1 :(得分:2)

您可以将%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)  
       )