将python读取配置文件规范了, 以后可以直接拷贝这个函数,
不用再写了;
import yaml
import os, sys
import argparse
from lib.mytool import MySqlTools
class GetMyCfg:
def __init__(self, file_name):
os.chdir(sys.path[0])
try:
cfg_file = open(file_name, 'r', encoding='utf-8')
except Exception:
print('file %s not found!' % file_name)
return
else:
self.cfg_data = yaml.load(cfg_file, Loader=yaml.FullLoader)
cfg_file.close()
def get(self, tag):
return self.cfg_data.get(tag, None)
def read_cfg(default_cfg):
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='config file', type=str, default=None)
args = parser.parse_args()
file_name = args.file
if not file_name:
file_name = default_cfg
if os.path.isfile(file_name):
return file_name
else:
return None
if __name__ == '__main__':
default_cfg = 'cfg.yml'
config_file = read_cfg(default_cfg)
my_cfg = GetMyCfg(config_file)
mysql_cfg = my_cfg.get('mysql')
mysql_cfg['db'] = 'easyops'
mysql_conn = MySqlTools('mysql', **mysql_cfg)
res = mysql_conn.select('select * from app_info order by id desc limit 10;')
print(res)
print(type(res))
mysql_conn.close()
网友评论