在 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屋!