1.实现简单的shell sed替换功能:
1 find_str='我有太多歌曲永远不会被唱起' 2 replace_str='YOUTAIDUODEGEQUYONGYUANBUHUIBEICHANGQI' 3 4 with open('yesterday','r',encoding='utf-8') as f, 5 open('yesterday.bak','w',encoding='utf-8') as f_new: 6 for line in f: # f为一个迭代器,按行迭代 7 if find_str in line: 8 line = line.replace(find_str, replace_str) # 字符串替换replace函数 9 f_new.write(line)
2.修改haproxy配置文件(节点搜索、添加和删除):
1 while True: 2 3 menu=input(''' 4 ------请选择功能------ 5 搜索节点请输入S: 6 添加节点请输入A: 7 删除节点请输入D: 8 退出请输入Q: 9 ''',) 10 11 if menu=='S': 12 website=input('请输入网址:') 13 node='backend'+' '+website 14 with open('haproxy.txt','r',encoding='utf-8') as f: 15 count=0 16 N=-2 17 for line in f:#使用迭代占用内存小 18 if line.strip()==node:#去掉两边空格之后判断 19 N=count 20 if count==N+1: 21 print('''节点{_website}信息为:{_info} 22 '''.format(_website=website,_info=line.strip())) 23 count+=1 24 if N==-2: 25 print('该节点不存在') 26 print(N) 27 28 elif menu=='A': 29 website=input('请输入您要添加的节点网址:') 30 server=input('请输入您要添加的节点地址:') 31 weight=input('请输入您要添加的节点weight:') 32 maxconn=input('请输入您要添加的节点maxconn:') 33 backend='backend'+' '+website 34 record=' '+'server'+' '+server+' '+'weight'+' '+weight+' '+'maxconn'+' '+maxconn 35 36 with open('haproxy.txt','a',encoding='utf-8') as f: 37 f.write(' ') 38 f.write(backend) 39 f.write(' ') 40 f.write(record) 41 print('添加成功') 42 43 elif menu=='D': 44 45 website=input('请输入您要删除的节点网址:') 46 backend='backend'+' '+website 47 48 with open('haproxy.txt','r',encoding='utf-8') as f_read: 49 readlines = f_read.readlines() 50 with open('haproxy.txt','w',encoding='utf-8') as f_write: 51 52 count=0 53 N=-2 54 for line in readlines: 55 count+=1 56 if line.strip()==backend:#删除网址 57 N=count 58 continue 59 if count==N+1:#删除节点信息 60 print('已删除节点信息') 61 continue 62 f_write.write(line) 63 64 if N==-2: 65 print('不存在该节点') 66 for line in readlines: 67 f_write.write(line) 68 elif menu=='Q': 69 break 70 else: 71 print('输入不合法')