def select(arg):
result = []
flag = False #设置标记点
with open("haproxy.txt", "r+", encoding="utf-8") as f:
for line in f: #逐行读文件
if line.strip() == "backend %s" % arg:
flag = True
continue
if line.strip().startswith("backend"):
flag = False
if flag:
result.append(line)
return result
def add():
inf_tmp = input("""input info: """)
inf = eval(inf_tmp)
if select(inf['backend']): #判断是否存在
return print(("the url exist"))
else:
with open("haproxy.txt", "r+", encoding="utf-8") as f:
for line in f:
f.write("\nbackend {url}\n".format(url = inf['backend']))
f.write("\t\tserver {red1} weight {num1} maxconn {num2}\n".format(red1 = inf['record']['server'],
num1 = inf['record']['weight'],
num2 = inf['record']['maxconn']))
return print("Adding record successfully.")
def remove():
del_inf = eval(input("delete info: "))
if select(del_inf['backend']): #判断是否存在
with open("haproxy.txt", "r+", encoding='utf-8') as file:
file_tmp = open("haproxy_tmp.txt", 'w')
line_ful = "backend {website}\n".format(website=del_inf['backend'])
for line in file:
if 'backend' not in line:
file_tmp.write(line)
elif line != line_ful:
file_tmp.write(line)
else:
print('Delete {line} \t\t{content}\n'.format(line=line, content=file.readline().strip()))
file_tmp.close()
file_tmp = open("haproxy_tmp.txt", 'r')
with open("haproxy.txt", "w", encoding='utf-8') as file:
for line in file_tmp:
file.write(line)
file_tmp.close()
return print("delect successfully")
else:
return print("error!")
def sel():
url = input("url: ")
ret = select(url)
for i in ret:
print(i)
while True:
choice = input("select, add, delete, quit: ")
if choice == "select":
sel()
elif choice == "add":
add()
elif choice == "delete":
remove()
elif choice == "quit":
break
ps:有个小问题,删除的时候不能把空行删除,请大神指教
需要建两个文件:“haproxy.txt","haproxy_tmp.txt"