argparse可选参数

时间:2012-08-01 13:36:02

标签: python argparse

我在python中有以下代码:

group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', dest='name_to_add', help='Add a new group or a role to existing group')
group.add_argument('-u', '--upgrade', dest='name_to_upgrade', help='Upgrade a group with the new version')
group.add_argument('-r', '--remove', dest='name_to_remove', help='Remove a group')
group.add_argument('-l', '--list', dest="list_server_or_group_name", help='Get group or server state/configuration')

我的问题是“-l”选项。我希望能够列出一个特定的组并列出所有组。目前我这样做:

“python my_script.py -l group_name” - 用于列出特定组 和 “python my_script.py -l all” - 用于列出所有组。

但我想列出所有组: “python my_script.py -l”。 我应该如何更改代码以便能够以这种方式运行它?以后如何在代码中查看它?

谢谢Arshavski Alexander。

1 个答案:

答案 0 :(得分:4)

optparse无法做到这一点。

但是,如果您从optparse切换到argparse(从2.73.2开始),您可以通过nargs='?'

  

'&#39 ;.如果可能,将从命令行使用一个参数,并将其作为单个项生成。如果不存在命令行参数,则将生成默认值。

group.add_argument('-l', '--list', dest="list_server_or_group_name",
                   help='Get group or server state/configuration',
                   nargs='?', default=None, const='all')