在单个命令行中多次调用同一子命令 [英] Multiple invocation of the same subcommand in a single command line
问题描述
我正在尝试弄清楚如何使用argparser执行以下操作:
I'm trying to figure out how to use argparser to do the following:
$ python test.py executeBuild --name foobar1 executeBuild --name foobar2 ....
getBuild
本身是一个子命令.我的目标是使脚本具有链接一系列子命令(executeBuild
是其中之一)并按顺序执行它们的能力.在上面的示例中,它将执行构建,然后设置环境,然后再次执行构建.如何使用argparse完成此操作?我尝试了以下方法:
getBuild
itself is a sub-command. My goal is to have the script have the capability to chain a series of sub-command (executeBuild
being one of them) and execute them in order. In the example above, it would execute a build, then setup the environment, then execute build again. How can I accomplish this with argparse? I've tried the following:
main_parser = argparse.ArgumentParser(description='main commands')
subparsers = main_parser.add_subparsers(help='SubCommands', dest='command')
build_parser = subparsers.add_parser('executeBuild')
build_parser.add_argument('--name', action='store', nargs=1, dest='build_name')
check_parser = subparsers.add_parser('setupEnv')
args, extra=main_parser.parse_known_args()
但是,看来无论何时执行此操作,它都会进入executeBuild
的子命令并报告它不知道executeBuild
是什么.我尝试解析出额外的内容,以便可以执行重复调用/链,但是,第一个视图属性似乎已被覆盖,因此我什至不能只保存额外的选项并进行遍历.
However, it appears that whenever I do this, it goes into the subcommand of executeBuild
and report it doesn't know what executeBuild
is. I've tried parsing out the extra so I can do a repeat call / chain, however, the first view property appears to have been overwritten, so I can't even just save the extra options and iterate thru.
推荐答案
您正在询问argparse
并非为之编写的内容:它很好地解析了一个命令行(但只有一个),并且您想解析多个命令在一行中.恕我直言,您必须对参数数组进行初始拆分,然后在每个子命令上使用argparse
.接下来的函数接受一个参数列表(可以是sys.argv
),跳过从每个已知子命令开始的数组中剩余的第一个数组和拆分数组.然后,您可以在每个子列表上使用argparse:
You are asking argparse
something it was not written for : it is good at parsing one command line (but only one) and you want to parse multiple commands in one single line. IMHO, you have to do an initial splitting on your arguments array, and then use argparse
on each subcommand. Following function takes a list of arguments (could be sys.argv
), skips the first and split remaining in arrays beginning on each known subcommand. You can then use argparse on each sublist :
def parse(args, subcommands):
cmds = []
cmd = None
for arg in args[1:]:
if arg in (subcommands):
if cmd is not None:
cmds.append(cmd)
cmd = [arg]
else:
cmd.append(arg)
cmds.append(cmd)
return cmds
在您的示例中:
parse(['test.py', 'executeBuild', '--name', 'foobar1', 'executeBuild', '--name', 'foobar2'],
('executeBuild',))
=>
[['executeBuild', '--name', 'foobar1'], ['executeBuild', '--name', 'foobar2']]
限制:子命令用作保留字,不能用作选项参数.
Limits : subcommands are used as reserved words and cannot be used as option arguments.
这篇关于在单个命令行中多次调用同一子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!