1.函数解耦:
fetch()和change()函数中均用到文件处理的操作,所以定义file_handler()做统一处理,防止fetch和change中都夹杂文件处理的内容,增强代码的可读性和维护性
#!user/bin/env python # -*- coding:utf-8 -*- import os def file_handler(backend_data,res=None,type='fetch'): #位置参数在左,默认参数在右 # print(backend_data) if type == 'fetch': with open('haproxy.conf','r') as read_f: li = [] tag = False for read_line in read_f: # print(read_line) if read_line.strip() == backend_data: tag = True continue if tag and read_line.startswith('backend'): #找到backend 并且 下一行以backend开头(加上tag防止在目标行之前先找到backend) break if tag: print('