continue
Let's say you have an argument parser like below, with a usual workflow that parses CLI args via parser.parse_args()
.
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-arg1")
parser.add_argument("-arg2", default="some default value")
However, I also may want to bypass argument parsing and supply args directly via a dictonary, which may not contain optional arguments. All missing arguments should be supplied by the parser defaults.
I.e., desirable scenario:
mydict={"arg1": "Supplied value"} # only supplied non-optional args
args = somehow_resolve_this(parser, mydict)
# this should now work
args.arg1
# Supplied value
print(args.arg2)
# Some default value
An equivalent question would be: How can I obtain all optional argument names and default values from the parser?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
dict
转换为argparse.Namespace
,然后将其输入.parse_args
,如下所示说明:转换
dict
使用解包**
将其输入到argparse.Namespace
的 kwargs 中,然后将其输入到parser.parse_args
You might convert your
dict
intoargparse.Namespace
and then feed it into.parse_args
as followsExplanation: convert
dict
into kwargs forargparse.Namespace
using unpacking**
then feed it intoparser.parse_args
continue
As long as none of the arguments is required (positional or flagged), we can get the default values with:
And we can 'update' that with your dict:
Using the idea of creating a namespace and passing that to the parser:
Here I supplied the
[]
argv
. That could be omitted if you still want to read the users input. This use of anamespace
parameter in effect sets/replaces all the defaults. (this could fail, though, if you are using subparsers).What if there are required arguments? Defaults don't matter with required arguments.
Another way to get the defaults, is to extract them from the
actions
list: