config.py 文件
"""config"""
import os
import yaml
import jmespath
import logging
class YamlUtil:
def __init__(self, config_path):
"""初始化配置类."""
self._cache = yaml.full_load(open(config_path, encoding="utf-8"))
self.fp = config_path
def get_config(self, cfg_path, defval=None):
cfg = self._cache
if cfg is None:
return defval
rv = jmespath.search(cfg_path, cfg)
if rv is None:
return defval
return rv
def flush(self):
'''将配置写入磁盘文件。'''
with open(self.fp, 'w+', encoding='utf8') as ffw:
yaml.dump(self._cache, ffw, allow_unicode=True,
indent=4, default_flow_style=False, sort_keys=False)
return True
def set_config(self, key, val, flush=False):
'''设置配置'''
if self._cache:
v = self._cache
for k in key.split('.')[:-1]:
if k not in v:
v[k] = {}
v = v[k]
v[key.split('.')[-1]] = val
if flush:
self.flush()
def create_config():
pkg_root_dir = os.path.dirname(__file__)
temp_path = os.path.join(pkg_root_dir,'config.yml')
config = YamlUtil(temp_path)
return config
CONFIG = create_config()
if __name__ == '__main__':
config = YamlUtil(r'./config2.yml')
data = CONFIG.get_config("IP_list", "ok")
print(data, type(data))
config的配置文件:
server_list:
- server:
server_ip: "192.168.xx.xx"
username : "admin"
password: "xxxx"
remote_name: "DESKTOP-HJxxxx"
file_info:
file_name: 全部结果_AI.csv
file_path: D:/aaaaaaa
dir_name: el_result
merge_file_name: 结果_AI.csv
local_computer_name: "WIN-9U4BSQ3xxx"