Python 使用argparse'实现两个位置参数;s`add_subparsers`方法

Python 使用argparse'实现两个位置参数;s`add_subparsers`方法,python,arguments,command-line-arguments,argparse,Python,Arguments,Command Line Arguments,Argparse,我想在使用argparse库的add_subparsers方法时获得以下功能,而不使用关键字参数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_a

我想在使用
argparse
库的
add_subparsers
方法时获得以下功能,而不使用关键字参数
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文本

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

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

使用
add_subparser
时,您基本上是在创建一个嵌套的解析器:

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
您可以让每个端点调用一个函数,方法是在相关子parser上使用
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!
>>def CREAR\u你好(args):
...     打印“你尖叫你好!”
...
>>>语法分析器\u cream\u hello.set\u默认值(func=cream\u hello)
>>>parser.parse_args(['scream','hello']))
命名空间(func=)
>>>args=parser.parse_args(['cream','hello'])
>>>args.func(args)
你尖叫着打招呼!

当我执行
$python my_program
时,我得到
用法:dummy.py[-h]{cream,count}…
my_program.py:错误:参数太少
。知道我如何在没有任何参数的情况下优雅地消除调用中的错误行吗?@Bentley4--当你添加子parser时,你是在暗示应该调用其中一个。如果您想让它做一些不同的事情,可以提前处理
sys.argv
。(
如果len(sys.argv)==1:sys.exit()
)或
如果len(sys.argv)==1:sys.argv.append('scream')
…我选择了mgilson的答案,因为我发现他的代码示例更容易理解。但是你解释得很好,谢谢!