一、configparser安装
pip3 install configparser
二、新建config.ini
[ENV] env = QA1 [QA1] url = https://qa1-xxx.cn s_url = https://qa-s-xxx.cn [QA2] url = https://qa2-xxx.cn s_url = https://qa-s-xxx.cn
三、封装操作config方法,operate_config.py
# -*- coding:utf-8 -*- import yaml import configparser from conf.setting import CONFIG_FILE,LOGIN_DATA_YAML_FILE def get_yaml(goal): with open(LOGIN_DATA_YAML_FILE, encoding='utf-8') as f: yaml_log = yaml.load(f, Loader=yaml.FullLoader) goal_list = yaml_log.keys() if goal in goal_list: return yaml_log[goal] else: print('不存在的配置') class OperateConfig: def __init__(self): self.config = configparser.ConfigParser() # 调用外部的读取配置文件的方法 self.config.read(CONFIG_FILE, encoding='GBK') def get_node_value(self,node, name): value = self.config.get(node, name) return value def set_node_value(self,section,node,name): """写入配置文件""" self.config.set(section,node,name) # 修改指定section 的option self.config.write(open(CONFIG_FILE, 'w'))
四、新建test_conf.py
from tools.operate_config import OperateConfig class TestConf: def test_1(self): # 读取配置文件 env = OperateConfig().get_node_value('ENV','env') print(env) # 修改配置文件,改成QA2 OperateConfig().set_node_value('ENV','env','QA2')
五、执行结果
读取配置文件的结果如下图:
修改配置文件的结果如下图:
标签:node,配置文件,Python,self,yaml,模块,config,configparser From: https://www.cnblogs.com/Chilam007/p/16899674.html