config.json 配置文件
{
"video_config": {
"alart_interval": 60,
"video_notify_url": "123456"
}
}
app_conf.py 配置文件操作模块
import json
# 读取配置
def read_config():
with open("config.json") as json_file:
config = json.load(json_file)
return config
# 从参数更新配置
def update_config(config):
with open("config.json", 'w') as json_file:
json.dump(config, json_file, indent=4,ensure_ascii=False)
return None
# 从全局变量更新配置
def save_config():
update_config(config)
# 把配置从配置文件读取到变量
config = read_config()
handle.py 执行具体任务,引用配置值
from app_conf import *
globals().update(config) #把app_conf中的config字典中的键值对变成变量
# 打印当前配置值
def execute():
print(video_config["video_notify_url"])
main.py 更新配置值,调用handle中方法,保证handle使用最新配置
from app_conf import *
from handle import *
globals().update(config) #把app_conf中的config字典中的键值对变成变量
execute() # 执行handle中方法,打印配置值
video_config["video_notify_url"] = '123456' # 修改配置值,video_config["video_notify_url"] 是 app_conf中config["video_config"]["video_notify_url"],执行globals().update(config)后可以简化调用方式
execute() # 执行handle中方法,打印配置值,配置值已修改
save_config() # 执行app_conf中保存方法,把更新后的值保存到配置文件
execute()
本文介绍如何在Python中读取、修改JSON配置文件,并在不同模块间同步配置更新。通过app_conf.py模块处理配置,handle.py模块执行任务并引用配置,main.py模块更新配置并确保handle.py使用最新配置。
599

被折叠的 条评论
为什么被折叠?



