pythonimport json
from typing import Any, Dict
pythondef load_config(config_file: str) -> Dict[str, Any]:
"""
读取配置文件,获取配置参数。
输入:
config_file (str): 配置文件路径。
输出:
(Dict[str, Any]): 配置参数字典。
"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f"配置文件 {config_file} 不存在,请检查文件路径。")
return {}
except json.JSONDecodeError:
print(f"配置文件 {config_file} 格式错误,请检查 JSON 格式。")
return {}
except Exception as e:
print(f"读取配置文件 {config_file} 时发生错误:{e}")
return {}
代码思路:
导入所需的库。
定义 load_config
函数,输入为配置文件路径,输出为配置参数字典。
使用 with open
语句打开文件,并利用 json.load
读取 JSON 配置文件内容。
如果文件不存在、JSON 格式错误或发生其他异常,捕获异常并进行相应的错误提示。
单元测试部分:
请先准备一个正确格式的 JSON 配置文件,例如 config.json
:
json{
"key1": "value1",
"key2": 42,
"key3": {
"sub_key1": true
}
}
然后在 Ipython Notebook 上进行以下测试:
python# 测试正确的配置文件
config_file = "config.json"
config = load_config(config_file)
assert config == {
"key1": "value1",
"key2": 42,
"key3": {
"sub_key1": true
}
}
print("正确的配置文件测试通过")
# 测试不存在的配置文件
config_file = "non_existent_config.json"
config = load_config(config_file)
assert config == {}
print("不存在的配置文件测试通过")
# 测试格式错误的配置文件
with open("error_config.json", "w", encoding='utf-8') as f:
f.write('{"key1": "value1", "key2": 42, "key3": {"sub_key1": true},}')
config_file = "error_config.json"
config = load_config(config_file)
assert config == {}
print("格式错误的配置文件测试通过")