使用argparse参数作为关键字参数 [英] Using argparse arguments as keyword arguments
问题描述
比方说,用argparse解析命令行后,我有了一个args
命名空间.现在,我想用它来创建一些像这样的对象:
Let's say I have an args
namespace after parsing my command line with argparse. Now, I want to use this to create some objects like this:
foo = Foo(bar=args.bar)
不幸的是,我限制了如果设置了关键字参数,则该参数不能为None
.现在,我需要检查是否设置了args.bar
并采取相应措施:
Unfortunately, I have the restriction that if a keyword argument is set, it must not be None
. Now, I need to check if args.bar
is set and act accordingly:
if args.bar:
foo = Foo(bar=args.bar)
else:
foo = Foo()
这很笨拙,无法扩展更多的参数.我想拥有的是这样的:
This is unwieldy and doesn't scale for more arguments. What I'd like to have, is something like this:
foo = Foo(**args.__dict__)
但是这仍然困扰着我最初的问题,并且对于不是__init__
方法的关键字参数的键也不起作用.有没有实现这些目标的好方法?
but this still suffers from my initial problem and additionally doesn't work for keys that are not keyword arguments of the __init__
method. Is there a good way to achieve these things?
推荐答案
您可以尝试以下方法:
>>> defined_args = {k:v for k,v in args._get_kwargs() if v is not None}
>>> foo = Foo(**defined_args)
例如:
>>> import argparse
>>> args = argparse.Namespace(key1=None,key2='value')
>>> {k:v for k,v in args._get_kwargs() if v is not None}
{'key2': 'value'}
但是,请注意,_get_kwargs()
不是公共API的一部分,因此将来的发行版/版本中可能会或可能不会提供.
Note, however, that _get_kwargs()
is not part of the public API so may or may not be available in future releases/versions.
这篇关于使用argparse参数作为关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!