4

我想在使用库的add_subparsers方法argparse而不使用关键字参数的情况下获得以下功能nargs

$ python my_program.py scream Hello
You just screamed Hello!!
$ python my_program.py count ten
You just counted to ten.

我知道我可以这样做:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("cmd", help="Execute a command", action="store",
  nargs='*')
args = parser.parse_args()
args_list = args.cmd

if len(args.cmd) == 2:
    if args.cmd[0] == "scream":
        if args.cmd[1] == "Hello":
            print "You just screamed Hello!!"
        else:
            print "You just screamed some other command!!"

    elif args.cmd[0] == "count":
        if args.cmd[1]:
            print "You just counted to %s." % args.cmd[1]
        else:
            pass

    else:
        print "These two commands are undefined"

else:
    print "These commands are undefined"

但是当我这样做时,$ python my_program.py我会丢失显示参数列表等的默认 arparse 文本。

我知道库中有一种add_subparsers方法argparse可以处理多个位置参数,但我还没有找到让它正常工作的方法。谁能告诉我怎么做?

4

2 回答 2

7
import argparse

def scream(args):
    print "you screamed "+' '.join(args.words)

def count(args):
    print "you counted to {0}".format(args.count)

parser = argparse.ArgumentParser()

#tell the parser that there will be subparsers
subparsers = parser.add_subparsers(help="subparsers")

#Add parsers to the object that was returned by `add_subparsers`
parser_scream = subparsers.add_parser('scream')

#use that as you would any other argument parser
parser_scream.add_argument('words',nargs='*')

#set_defaults is nice to call a function which is specific to each subparser
parser_scream.set_defaults(func=scream) 

#repeat for our next sub-command
parser_count = subparsers.add_parser('count')
parser_count.add_argument('count')
parser_count.set_defaults(func=count)

#parse the args
args = parser.parse_args()
args.func(args)  #args.func is the function that was set for the particular subparser

现在运行它:

>python test.py scream Hello World!  #you screamed Hello World!
>python test.py count 10             #you counted to 10
于 2012-09-06T17:10:15.787 回答
2

使用时,add_subparsers您基本上是在创建嵌套解析器:

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')

parser_scream = subparsers.add_parser('scream', help='scream help')

现在你有了一个的解析器对象,你可以添加开关。或者,您可以添加另一层嵌套:

scream_subparsers = parser_scream.add_subparsers(help='scream sub-command help')
parser_scream_hello = scream_subparsers.add_parser('hello', help='scream hello help')

这可以深入到您需要控制精确格式的程度。每个级别都提供帮助:

>>> parser.print_help()
usage: [-h] {scream} ...

positional arguments:
  {scream}    sub-command help
    scream    scream help

optional arguments:
  -h, --help  show this help message and exit
>>> parser_scream.print_help()
usage:  scream [-h] {hello} ...

positional arguments:
  {hello}     scream sub-command help
    hello     scream hello help

optional arguments:
  -h, --help  show this help message and exit
>>> parser_scream_hello.print_help()
usage: scream hello [-h]

optional arguments:
  -h, --help  show this help message and exit

您可以让每个端点调用一个函数,方法set_defaults(func=yourfunction)是在有问题的子解析器上使用,然后使用该默认func参数为当前参数调用所选函数:

>>> def scream_hello(args):
...     print "You screamed hello!"
...
>>> parser_scream_hello.set_defaults(func=scream_hello)
>>> parser.parse_args(['scream', 'hello'])
Namespace(func=<function scream_hello at 0x10bd73c80>)
>>> args = parser.parse_args(['scream', 'hello'])
>>> args.func(args)
You screamed hello!
于 2012-09-06T17:24:48.723 回答