使用argparse(python)创建变量键/值对 [英] Create variable key/value pairs with argparse (python)
问题描述
我使用 argparse
模块来设置我的命令行选项。我也使用 dict
作为我的应用程序中的配置。简单的键/值存储。
我正在寻找的是使用命令行参数重写JSON选项的可能性,而不提前定义所有可能的参数。像 - conf-key-1 value1 --conf-key-2 value2
,这将创建一个dict {'key_1':'value1 ','key_2':'value2'}
(参数中的' - '由dict中的'_'替换)。然后我可以结合这个dict和我的JSON配置(dict)。
所以基本上我想定义 - conf - *
作为参数,其中 *
可以是任何键,后面是值
p>
我找到了 configargparse
模块,但就我所见,我开始用
我可以用这种方法吗?
我尝试的第一件事是使用 parse_known_args
来处理其他参数,并处理 extras
与我的例行。在 argparse
中添加--conf-处理将更有效。
argv ='--conf-key-1 value1 --conf-key-2 value2'.split()
p = argparse.ArgumentParser()
args,extras = p.parse_known_args )
def foo(astr):
如果astr.startswith(' - conf-'):
astr = astr [7:]
astr = astr .replace(' - ','_')
return astr
d = {foo(k):v for k,v in zip(extras [:: 2],extras [1 :: 2])}
#{'key_1':'value1','key_2':'value2'}
extras
解析可以更强大 - 确保有合适的对,拒绝错误形成的键,处理 =
。
另一种方法是为扫描
sys.argv
code>字符串,并使用它们构造 add_argument
语句。
keys = [k for argv if k.startswith(' - conf-')]
p = argparse.ArgumentParser()
在键中的k:
p.add_argument k,dest = foo(k))
print vars(p.parse_args(argv))
< hr>
如果您接受--conf key1 value1 --conf key2 value2 ...作为输入,您可以定义
parser.add_argument(' - conf',nargs = 2,action ='append')
这将产生:
命名空间('conf':[['key1 ','value1'],['key2','value2']])
变成字典。或者自定义 Action
可以使用 setattr(namespace,values [0],values [1])
/ value对直接写入命名空间。
我相信有关于接受key1:valuekey2:value2 / p>
I'm using argparse
module to set my command line options. I'm also using a dict
as a config in my application. Simple key/value store.
What I'm looking for is a possibility to override JSON options using command line arguments, without defining all possible arguments in advance. Something like --conf-key-1 value1 --conf-key-2 value2
, which would create a dict {'key_1': 'value1','key_2': 'value2'}
('-' in the argument is replaced by '_' in the dict). Then I can combine this dict with my JSON config (dict).
So basically I would like to define --conf-*
as an argument, where *
can be any key and what comes after is the value
.
I did find configargparse
module, but as far as I can see I start with a dict
I already use.
Any ideas how I could approach this?
The first thing I'd try is use parse_known_args
to handle other arguments, and handle the list of extras
with my on routine. Adding the '--conf-' handling to argparse
would be more work.
argv = '--conf-key-1 value1 --conf-key-2 value2'.split()
p = argparse.ArgumentParser()
args, extras = p.parse_known_args(argv)
def foo(astr):
if astr.startswith('--conf-'):
astr = astr[7:]
astr = astr.replace('-','_')
return astr
d = {foo(k):v for k,v in zip(extras[::2],extras[1::2])}
# {'key_1': 'value1', 'key_2': 'value2'}
The extras
parsing could be more robust - making sure that there are proper pairs, rejecting badly formed keys, handling =
.
Another approach would be to scan sys.argv
for --conf-
strings, and use those to construct add_argument
statements.
keys = [k for k in argv if k.startswith('--conf-')]
p = argparse.ArgumentParser()
for k in keys:
p.add_argument(k, dest=foo(k))
print vars(p.parse_args(argv))
If you would accept '--conf key1 value1 --conf key2 value2 ...' as the input, you could define
parser.add_argument('--conf', nargs=2, action='append')
which would produce:
namespace('conf': [['key1','value1'],['key2','value2']])
which could easily be turned into a dictionary. Or a custom Action
could use setattr(namespace, values[0], values[1])
to enter the key/value pairs directly into the namespace.
I believe there have been SO question(s) about accepting '"key1:value" "key2:value2"' inputs.
这篇关于使用argparse(python)创建变量键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!