在argparse中使用变量arg名称 [英] Using variable arg names with argparse
问题描述
我有一个上游系统,它使用不同的arg名称来调用我的程序.示例:
I have an upstream system that invokes my program with varying arg names. Example:
foo --xyz1 10 --xyz2 25 --xyz3 31
我希望argparsing的结果是xyz = [10,25,31].
I would like the result of argparsing to be a xyz = [10, 25, 31].
我的args的名称有一个通用前缀,但不幸的是,至少必须具有不同的数字后缀,这也表示顺序.我也没有固定数量的参数.
The names of my args have a common prefix, but unfortunately have to differ at least with a different numeric suffix, which also indicates order. I also don't have a fixed number of args.
是否可以使用argparse对此建模?通过内置功能的某种组合,或者通过重写/插入一些自定义解析器处理,可以提供可用的功能.
Is there a way to model this with argparse? Either with what is available through some combination of built-in capabilities, or by overriding/pluging in some custom parser handling.
推荐答案
我建议进行一些预处理以实现此目的:
I would suggest a bit of pre-processing to achieve this:
代码:
def get_xyz_cmd_line(xyz_cmd_line):
# build a generator to iterate the cmd_line
cmd_line_gen = iter(xyz_cmd_line)
# we will separate the xyz's from everything else
xyz = []
remaining_cmd_line = []
# go through the command line and extract the xyz's
for opt in cmd_line_gen:
if opt.startswith('--xyz'):
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))
else:
remaining_cmd_line.append(opt)
# sort the xyz's and return all of them as -xyz # -xyz # ...
return list(it.chain(*[
('--xyz', x[1]) for x in sorted(xyz)])) + remaining_cmd_line
要测试:
import argparse
import itertools as it
parser = argparse.ArgumentParser(description='Get my Option')
parser.add_argument('--an_opt', metavar='N', type=int,
help='An option')
parser.add_argument('--xyz', metavar='N', type=int, action='append',
help='An option')
cmd_line = "--an_opt 1 --xyz1 10 --xyz3 31 --xyz2 25 ".split()
args = parser.parse_args(get_xyz_cmd_line(cmd_line))
print(args)
输出:
Namespace(an_opt=1, xyz=[10, 25, 31])
要使用:
名义上而不是上面的示例中的固定cmd_line
,将使用类似以下内容的名称进行调用:
Nominally instead of a fixed cmd_line
as in the above example this would be called with something like:
args = parser.parse_args(get_xyz_cmd_line(sys.argv[1:]))
更新:如果需要--xyz = 31(即=
分隔符):
UPDATE: If you need --xyz=31 (ie =
separator):
然后您需要更改:
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))
收件人:
if '=' in opt:
xyz.append(tuple(opt.split('=', 1)))
else:
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))
这篇关于在argparse中使用变量arg名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!