码迷,mamicode.com
首页 > 编程语言 > 详细

Python-Day3

时间:2018-02-10 22:40:02      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:print   odi   utf-8   tin   检查   body   pass   []   end   

技术分享图片

#Author:ZhaoBin
#实现对Haproxy配置文件的增删改查

def fetch(backend):
result = []
with open(‘ha.conf‘,‘r‘,encoding=‘utf-8‘) as f:
flag = False
for line in f:
if line.strip().startswith("backend") and line.strip() == "backend " + backend:
flag = True
continue
if flag == True and line.strip().startswith("backend"):
flag = False
break
if flag == True and line.strip():
result.append(line.strip())
return result

def add(backend,record):
#先检查记录是否存在
record_list=fetch(backend)
print(record_list)
if not record_list:
#backend不存在
with open("ha.conf","r") as old, open("new.conf","w") as new:
for line in old:
new.write(line)
new.write("\nbackend " + backend+"\n")
new.write(" "*8 + record+"\n")
else:
#backend存在,record也存在
if record in record_list:
pass
else:
#backend存在,record不存在
record_list.append(record)
with open("ha.conf", "r") as old, open("new.conf", "w") as new:
flag = False
for line in old:
if line.strip().startswith("backend") and line.strip() == "backend " + backend:
flag = True
new.write(line)
for new_line in record_list:
new.write(" "*8+ new_line + "\n")
if flag and line.strip().startswith("backend"):
flag = False
new.write(line)
continue
if not flag and line.strip():
new.write(line)

#ret = fetch("www.oldboy.org")
# print(ret)

bk="www.oldboy.org"
rd="server 100.1.7.8 weight 10 maxconn 3000"
add(bk,rd)

 

Python-Day3

标签:print   odi   utf-8   tin   检查   body   pass   []   end   

原文地址:https://www.cnblogs.com/timangle026/p/8439804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!