0

我有一个选项,其中包含一个选项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用于生成帮助文本的对象?

4

2 回答 2

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如果您希望帮助看起来更整洁,您可以在作业中投入更多精力!

于 2015-02-04T16:39:11.307 回答
2

您可以%default输入帮助文本,它将扩展为该选项的默认值(请参阅文档)。

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

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)  
       )
于 2015-02-04T16:42:05.187 回答