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'+' '+website14 with open('haproxy.txt','r',encoding='utf-8') as f:15 count=016 N=-217 for line in f:#使用迭代占用内存小18 if line.strip()==node:#去掉两边空格之后判断19 N=count20 if count==N+1:21 print('''节点{_website}信息为:{_info}22 '''.format(_website=website,_info=line.strip()))23 count+=124 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'+' '+website34 record=' '+'server'+' '+server+' '+'weight'+' '+weight+' '+'maxconn'+' '+maxconn35 36 with open('haproxy.txt','a',encoding='utf-8') as f:37 f.write('\n')38 f.write(backend)39 f.write('\n')40 f.write(record)41 print('添加成功')42 43 elif menu=='D':44 45 website=input('请输入您要删除的节点网址:')46 backend='backend'+' '+website47 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=053 N=-254 for line in readlines:55 count+=156 if line.strip()==backend:#删除网址57 N=count58 continue59 if count==N+1:#删除节点信息60 print('已删除节点信息')61 continue62 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 break70 else:71 print('输入不合法')