一:三级菜单直接退出的方法(tag的用法)
tag=True
while tag:
print('level1')
choice=input('level1>>: ').strip()
if choice == 'quit':break
if choice == 'quit_all': tag = False
while tag:
print('level2')
choice=input('level2>>: ').strip()
if choice == 'quit': break
if choice == 'quit_all': tag = False
while tag:
print('level3')
choice = input('level3>>: ').strip()
if choice == 'quit': break
if choice == 'quit_all':tag=False
二:对文件处理 (增删改查)
import os
def file_handler(backend_data,res='None',type='fetch'):
if type == 'fetch':
with open('renkoupucha','r') as read_f:
tag=False #标识一种状态
ret=[]
for read_line in read_f:
if read_line.strip() == backend_data:#去除转行空格
tag=True
continue
if tag and read_line.startswith('backend'):
break
if tag:
print(read_line,end='')
ret.append(read_line)
return ret
elif type == 'change':
with open('renkoupucha', 'r')as read_f, \
open('renkoupucha_new', 'w')as write_f:
tag = False
has_write = False
for read_line in read_f:
if read_line.strip() == backend_data:
tag = True
continue
if tag and read_line.startswith('backend'):
tag = False
if not tag:
write_f.write(read_line)
else:
if not has_write:
for record in res:
write_f.write(record)
has_write = True
os.rename('renkoupucha', 'renkoupucha.bak')
os.rename('renkoupucha_new', 'renkoupucha')
os.remove('renloupucha.bak')
def fetch(data):
backend_data='backend %s' %data
return file_handler(backend_data)
def add():
pass
def change(data):
# print('这是修改功能')
print('用户输入的数据是',data)# data[0]#文档当中的一条记录
backend=data[0]['backend']
backend_data='backend %s' %backend
old_server_recored='%s server %s %s weight %s maxconn %s'%(' '*8,data[0]['record']['server'],
data[0]['record']['server'],
data[0]['record']['weight'],
data[0]['record']['maxconn'],)
new_server_recored = '%s server %s %s weight %s maxconn %s' % (' ' * 8, data[1]['record']['server'],
data[1]['record']['server'],
data[1]['record']['weight'],
data[1]['record']['maxconn'],)
print('用户想要修改的记录是',old_server_recored)
res = fetch(data[0]['backend'])
print(res)
if not res or old_server_recored not in res:
return '修改记录不存在'
else:
index=res.index(old_server_recored)
res[index]=new_server_recored #修改的列表
res.insert('%s\n' %backend_data )
res.insert(0,'%s\n' %backend_data)
file_handler(backend_data,res=res,type='change')
def delete():
pass
if __name__=='__main__':
msg='''
1:查询
2:添加
3:修改
4:删除
5:退出
'''
msg_dic={
'1':fetch,
'2':add,
'3':change,
'4':delete,
}
while True:
print(msg)
choice=input('请输入你的选项: ').strip()
if not choice:continue
if choice =='5':break
data=input('请输入你的数据:').strip()
if choice != '1':
data=eval(data)
res=msg_dic[choice](data)
print('最终结果',res)