通过解析器将JSON文件作为命令行参数传递,这种做法可行吗?

4
我需要通过命令行参数解析器将JSON文件参数覆盖为Python字典。由于JSON文件位于当前工作目录中,但其名称可以是动态的,因此我希望像下面这样做:

python python_script --infile json_file

python_script:

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()

1
好的,阅读Python文档应该足够了: 对于文件:https://docs.python.org/3/tutorial/inputoutput.html 对于JSON部分:https://docs.python.org/3.5/library/json.html 对于args:使用一个库。 - Cal Eliacheff
@fmarc 我已经尝试了上面的代码,我是 Python 的新手。我知道 json load 方法,但它只会加载特定的文件,而在我的情况下我不想要这个,谢谢。 - Code_x
1个回答

4

使用给定名称的JSON文件读取--infile并更新您的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)

太好了!这正是我在寻找的。谢谢你,@Nightcrawler。 - Code_x
2
有没有更加动态的解决方案?比如说你事先不知道字段名。如果有一个可以支持 Json 文件中参数的工具就太好了。 - Alex
我不太确定为什么你在那里加了"nargs=1"。有了它,结果会以列表的形式返回,你必须通过"infile[0]"进行索引,而没有它,你只需执行"json.load(arguments.infile)"即可。 - Keith
jsonargparse 包有一个很好的解决方案(以及更多),请参见 https://jsonargparse.readthedocs.io/en/stable/index.html#configuration-files。在我看来,这比自己编写 argparse 和 json 合并逻辑要好。 - schiavuzzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接