# coding:utf-8 import os import sys import yaml import redis import subprocess BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def _get_config_dir(): config_dir = os.path.join(BASE_DIR, 'supervisord/config/production_env') return config_dir def _load_ymal(path): with open(path, 'r') as fr: data = yaml.load(fr, yaml.FullLoader) if data is None: data = {} return data def get_monitor_config(): '''获取监控配置''' _config_dir = _get_config_dir() monitor_path = os.path.join(_config_dir, 'monitor.yml') monitor_data = _load_ymal(monitor_path) build_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'supervisord/build_monitor') monitor_data[build_dir] = { 'name': 'build', 'user': 'root', 'executable': sys.executable, 'filter': ['*_monitor.py'], 'exclude': [] } return monitor_data def get_redis_connection(): '''获取redis连接''' _config_dir = _get_config_dir() redis_path = os.path.join(_config_dir, 'redis.yml') result = _load_ymal(redis_path) data = result['connection'] host, port, db = data['host'], int(data['port']), int(data['db']) try: password = data['password'] except KeyError as e: password = None connection = redis.Redis(host=host, port=port, db=db, password=password, decode_responses=True) return connection def get_dingding_config(): _config_dir = _get_config_dir() path = os.path.join(_config_dir, 'dingding.yml') data = _load_ymal(path) return data def shell_cmd(cmd, is_wait=True): '''执行shell命令 :param is_wait 是否阻塞等待命令运行结束,Ture 表示阻塞模式 :return code, stdout, stderr code 命令运行状态码,0表示运行成功 stdout 命令运行输出结果 stderr 命令运行错误信息 ''' code, stdout, stderr = 0, '', '' proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if is_wait: stdout, stderr = proc.communicate() code = proc.returncode stdout = stdout.decode('utf-8').strip() stderr = stderr.decode('utf-8').strip() return code, stdout, stderr if __name__ == "__main__": con = get_redis_connection() print(con)