我需要通过命令行参数解析器将 json 文件参数覆盖到 python 字典中。由于 json 文件位于当前工作目录中,但它的名称可以是动态的,所以我想要如下所示的内容:-
python python_script --infile json_file
python_脚本:
if __name__ == "__main__":
profileInfo = dict()
profileInfo['profile'] = "enterprisemixed"
profileInfo['nodesPerLan'] = 50
json_文件:
{
"profile":"adhoc",
"nodesPerLan" : 4
}
我尝试添加以下行,但不知道如何将此 json 数据加载到 python 字典中:-
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', nargs = 1, help="JSON file to be processed",type=argparse.FileType('r'))
arguments = parser.parse_args()
请您参考如下方法:
读取给定 --infile 名称的 JSON 文件并更新您的 profileInfo:
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', nargs=1,
help="JSON file to be processed",
type=argparse.FileType('r'))
arguments = parser.parse_args()
# Loading a JSON object returns a dict.
d = json.load(arguments.infile[0])
profileInfo = {}
profileInfo['profile'] = "enterprisemixed"
profileInfo['nodesPerLan'] = 50
print(profileInfo)
# Overwrite the profileInfo dict
profileInfo.update(d)
print(profileInfo)
