day 03 --Haproxy 增加, 删除,查询
key 知识点:函数的定义, 函数的递归调用, flag 标志位的使用,eval() 函数
#!C:\Program Files\Python35\bin # -*- conding:utf-8 -*- # author: Frank def search_backend(): search_list=[] #定义一个空列表,存放所查到backend的信息 search_input = input("please input the backend which you want to search\n") with open ('Haproxy.cfg') as f: backend_flag = False #初始化标志位False for line in f: if line.strip()== 'backend %s'%search_input: #当匹配到所要查询的backend信息时,标志位为True,跳出本次循环,继续下一次循环 backend_flag = True continue if backend_flag and line.strip().startswith('backend'): #上一个if语句,将标志位置为True,当再次遇到以’backend‘ 开头时 #已经为下一个backend信息 break if backend_flag and line.strip(): # 将上两个if条件除外的行追加到列表 search_list,即我们想要的行 search_list.append(line.strip()) if len(search_list) == 0: print("\033[31;1m%s not exit, please re_input\033[0m"%search_input) search_backend() else: for node in search_list: #打印列表的每一行 print(node) def add_backend(): args = '''{ 'backend':'%s', 'record':{ 'server':'%s', 'weight':'%s', 'maxconn':'%s' } }'''%(input('backend:'),input('server:'),input('weight:'),input('maxconn:')) b = eval(args) with open('Haproxy.cfg','a+',encoding='utf-8') as f: #print(' ',file=f) print('backend %s'%b['backend'],file=f,flush=True) #通过两个print, 将backend, 和下面的一行从格式上区别开 print('\t\tserver %s weight %s maxconn %s'%(b['record']['server'],b['record']['weight'],b['record']['maxconn']),file=f,flush=True) def delete_backend(): # 删除正好和查询的思路相反,search 是将结果追加到列表里, delete是将所要删除的排除在外 with open('Haproxy.cfg','r') as f_ori, open('Haproxy_new.cfg','a+') as f_new: delete_input=input("please enter backend which you want to delete:") backend_flag=True for line in f_ori: if line.strip() == 'backend %s'%delete_input: backend_flag=False continue if line.strip().startswith('backend') and line.strip() != 'backend %s' %delete_input: backend_flag=True if backend_flag: #除删除之外的所有行写到一个新的文件里 f_new.write(line) Mesg = '''1. Search backend 2. Add backend 3. delete backend 4. quit ''' while True: print(Mesg) user_input = input("please input which do you want:") if user_input == "1": search_backend() elif user_input == "2": add_backend() elif user_input == "3": delete_backend() elif user_input == '4': exit() else: exit(print("Invaild input ,exit"))
#执行结果 1. Search backend 2. Add backend 3. delete backend 4. quit please input which do you want:1 please input the backend which you want to search www.baidu.com server 10.22.23.45 weight 20 maxconn 30000 1. Search backend 2. Add backend 3. delete backend 4. quit please input which do you want:2 backend:www.google.cn server:10.88.123.40 weight:20 maxconn:3400 1. Search backend 2. Add backend 3. delete backend 4. quit please input which do you want:4
定义三个函数
search_backend()
add_backend()
delete_backend()
对于add_backend() 和 delete_backend()函数都用到标志位(这里目前没有使用JSON)
1.如下文本信息,我要删除 www.baidu.com 所对应的信息, 采用for 循环和标志位的变换读出这两行信息
backend www.baidu.com server 10.22.23.45 weight 20 maxconn 30000 backend buy.oldboy.org server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000 server 100.1.7.93 100.1.7.93 weight 20 maxconn 300 search_list=[] with open ('Haproxy.cfg') as f: backend_flag = False #初始化标志位False for line in f: if line.strip()== 'backend www.baidu.com": #当匹配到所要查询的backend信息时,标志位为True,跳出本次循环,继续下一次循环 backend_flag = True
search_list.append(line.strip("\n") continue if backend_flag and line.strip().startswith('backend'): #上一个if语句,将标志位置为True,当再次遇到以’backend‘ 开头时 #已经为下一个backend信息 break if backend_flag and line.strip(): # 将上两个if条件除外的行追加到列表 search_list,即我们想要的行 search_list.append(line.strip())
2. search_backend() 使用函数的递归调用
if len(search_list) == 0: #没有查询到结果 print("\033[31;1m%s not exit, please re_input\033[0m"%search_input) search_backend()
3.eval()
eval 用法 : eval(expression,[globals=None,[locals=None]]
函数的作用:计算expression 的值,expression只能是单个运算表达式
- expression: 必选参数,eval() arg 1 must be a string, bytes or code object, 如果expression 是一个string,会被当成一个python 表达式进行分析和解释, 正是本代码中用到的
>>> a = '''{ ... 'backend':'www.baidu.com', ... 'record':{ ... 'weight':'20', ... 'maxconn':'3400' ... } ... }''' >>> a "{\n\t 'backend':'www.baidu.com',\n\t 'record':{\n\t\t\t'weight':'20',\n\t\t\t 'maxconn':'3400'\n\t\t }\n }" >>> eval(a) {'record': {'weight': '20', 'maxconn': '3400'}, 'backend': 'www.baidu.com'} >>>
- globals: optional 参数,表示全局命名空间,如果有,必须是一个字典对象
- locals: optional 参数,表示当前局部命名空间,可以是任意映射对象,如果省略,则与globals取相同的值
- 如果globals 和 locals都省略,eval()取被调用环境下的命名空间的值
返回值:
如果expression是一个code对象,且创建该code对象时,complie函数的mode参数是“exec”,那么eval()函数返回值为None
如果expression是一个输出语句,如print(),则eval()返回结果为None;
否则,expression表达式的结果就是eval()函数的返回值;
for instance:
>>> x=10 >>> y=20 >>> eval('x+y') 30 >>> eval('x+y',{'x':1,'y':2}) 3 >>> eval('x+y',{'x':1,'y':2},{'y':3,'z':4}) 4 >>> eval('print(x,y)') 10 20 >>> print(eval('print(x,y)')) 10 20 None