day3

程序1: 实现简单的shell sed替换功能

day3

import os,sys
old = sys.argv[]
new = sys.argv[]
file_name = sys.argv[]
tmp_file ="tmpfile"
open(tmp_file,"w")
file1 = open(file_name,"r")
file2 = open(tmp_file,"r+")
for line in file1:
if old in line:
line= str.replace(line,old,new)
file2.write(line)
if new not in line:
file2.write(line)
file2.flush()
file1.close()
file2.close() os.remove(file_name)
os.rename(tmp_file,file_name)
 程序2:修改haproxy配置文件 
day3
 
import os
def select(backend):
result = []
flag = False
with open("haproxy.conf","r",encoding="UTF-8") as f:
for line in f:
if line.strip() == "backend %s" %(backend):
flag = True
continue
if line.strip().startswith("backend"):
flag = False
if flag:
line = line.strip()
result.append(line)
for i in result:
if i == "":
result.remove(i)
for i in result:
print(i)
return i def append(backend):
with open("haproxy.conf","a",encoding="UTF-8") as f:
f.write("%sbackend %s%s%8sserver %s %s weight %s maxconn %s"%("\n",backend[],"\n","\b",backend[],backend[],backend[],backend[])) def delete(backend):
file1 = open("haproxy.conf","r",encoding="UTF-8")
file2 = open("haproxy.new","w+",encoding="UTF-8")
flag = False
for line in file1:
if backend in line:
flag = True
continue
elif flag:
flag = False
else:
file2.write(line)
file1.close()
file2.close()
os.remove("haproxy.conf")
os.renames("haproxy.new","haproxy.conf") def update(backend,select):
print("您要修改的是:%s"%(select))
delete(backend)
backend=[]
backend_message = input("例:www.baidu.com 192.168.1.1 200 2000\n请输入修改后的新信息:")
append(backend_message.split(" ")) if __name__ == "__main__":
while True:
print(u"%s\n1.查找记录\n2.添加记录\n3.删除记录\n4.修改记录\n5.退出程序\n"%("".center(,"-")))
case=int(input("case input number:"))
if case == :
backend=[]
backend_message = input("例:www.baidu.com 192.168.1.1 200 2000\n请输入相关信息:")
append(backend_message.split(" "))
elif case == :
select(input("例:www.baidu.com\n请输入要查找的backend:"))
elif case == :
delete(input("例:www.baidu.com\n请输入要删除的backend:"))
elif case == :
backend=input("例:www.baidu.com\n请输入要修改的backend:")
update(backend,select(backend))
elif case == :
exit("已经退出程序")
else:
print("\033[1;31;47m请输入正确case指令\033[0m")
 
 
上一篇:MFC程序运行流程


下一篇:macOS 为 Markdown 文件开启全文检索方法