gpt4 book ai didi

python - 使用 argparse 的 `add_subparsers` 方法实现两个位置参数

转载 作者:太空狗 更新时间:2023-10-30 02:22:08 26 4
gpt4 key购买 nike

我想在使用 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

关于python - 使用 argparse 的 `add_subparsers` 方法实现两个位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12304709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com