结合使用 Argparse 和 Json [英] Using Argparse and Json together

查看:33
本文介绍了结合使用 Argparse 和 Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的初学者.

I am a beginner to Python.

我想知道 Argparse 和 JSON 是否可以一起使用.说,我有变量 p,q,r

I wanted to know if Argparse and JSON could be used together. Say, I have variables p,q,r

我可以将它们添加到 argparse 中 -

I could add them to argparse as -

parser.add_argument('-p','--param1',help='x variable', required=True)
parser.add_argument('-q','--param2',help='y variable', required=True)
parser.add_argument('-r','--param3',help='z variable', required=True)

现在假设我想从 JSON 文件中读取相同的变量,可以这样做吗?所以我可以从命令行或 JSON 文件输入值.

Now suppose I wanted to read the same variables from JSON file, is it possible to do it? So I could input the values either from command line or a JSON file.

JSON 输入文件 -

JSON input file -

{
    "testOwner": "my name",
    "tests": [
        "test1",
        "test2",
        "test3"
    ],

    "testParameters": {
        "test1": {
            "param1": "0",
            "param2": "20",
            "param3" : "True"
        },

        "test2": {
            "param1": "cc"
        }
    }   
}

推荐答案

parse_args 中的 args 命名空间可以转换为字典:

The args Namespace from parse_args can be transformed into a dictionary with:

argparse_dict = vars(args)

JSON 值也在字典中,比如 json_dict.您可以将选定的值从一个字典复制到另一个字典,或者进行整体更新:

The JSON values are also in a dictionary, say json_dict. You can copy selected values from one dictionary to the other, or do a whole scale update:

argparse_dict.update(json_dict)

这样 json_dict 值会覆盖 argparse 值.

This way the json_dict values over write the argparse ones.

如果你想同时保留两者,你要么需要有不同的参数(键)名称,要么值必须是列表,你可以附加或扩展.这需要更多的工作,从在 argparse 中使用正确的 nargs 值开始.

If you want to preserve both, you either need to have different argument (key) names, or the values have to be lists, which you can append or extend. That takes a bit more work, starting with using the correct nargs value in argparse.

修改后的 parser 生成,带有测试输入:

The revised parser produces, with a test input:

In [292]: args=parser.parse_args('-p one -q two -r three'.split())
In [293]: args
Out[293]: Namespace(param1='one', param2='two', param3='three')
In [295]: args_dict = vars(args)    
In [296]: args_dict
Out[296]: {'param1': 'one', 'param2': 'two', 'param3': 'three'}

JSON 字符串,在解析时 (json.loads?) 生成如下字典:

The JSON string, when parsed (json.loads?) produces a dictionary like:

In [317]: json_dict
Out[317]: 
{'testOwner': 'my name',
 'testParameters': {'test1': {'param1': '0', 'param2': '20', 'param3': 'True'},
  'test2': {'param1': 'cc'}},
 'tests': ['test1', 'test2', 'test3']}

我通过将您的显示粘贴到我的 Ipython 会话中来生成此内容,但我认为 JSON 加载程序会生成相同的内容

I produced this by pasting your display into my Ipython session, but I think the JSON loader produces the same thing

argparse 值可以添加:

The argparse values could be added with:

In [318]: json_dict['testParameters']['test3']=args_dict
In [319]: json_dict
Out[319]: 
{'testOwner': 'my name',
 'testParameters': {'test1': {'param1': '0', 'param2': '20', 'param3': 'True'},
  'test2': {'param1': 'cc'},
  'test3': {'param1': 'one', 'param2': 'two', 'param3': 'three'}},
 'tests': ['test1', 'test2', 'test3']}

在这里,我将它添加为第三个 test 集,(巧合地)从 tests 列表中获取一个名称.json_dict['testParameters']['test2']=args_dict 将替换 test2 的值.

Here I added it as a 3rd test set, taking (by conincidence) a name from the tests list. json_dict['testParameters']['test2']=args_dict would replace the values of test2.

将 args 值添加到 'test2' 的未定义值的一种方法是:

One way to add the args values to the undefined values of 'test2' is:

In [320]: args_dict1=args_dict.copy()    
In [322]: args_dict1.update(json_dict['testParameters']['test2'])
In [324]: json_dict['testParameters']['test2']=args_dict1
In [325]: json_dict
Out[325]: 
{'testOwner': 'my name',
 'testParameters': {'test1': {'param1': '0', 'param2': '20', 'param3': 'True'},
  'test2': {'param1': 'cc', 'param2': 'two', 'param3': 'three'},
  'test3': {'param1': 'one', 'param2': 'two', 'param3': 'three'}},
 'tests': ['test1', 'test2', 'test3']}

我使用这个版本的 update 优先考虑 JSON 字典中的 'cc' 值.

I used this version of update to give priority to the 'cc' value in the JSON dictionary.

这篇关于结合使用 Argparse 和 Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆