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

python学习之配置文件查看,添加,删除配置程序(作业三)

时间:2016-02-04 01:08:11      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:

思维还有点乱,撸代码到深夜,先上代码吧.(我是跟着武sir的思路的)

流程图:

技术分享


代码(有注释):

技术分享
  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 import json,os
  4 def login():
  5     flag = False
  6     while True:
  7         username = input("Please enter a user name:")
  8         l = open(‘name_lock.txt‘,‘r‘)
  9         for lline in l.readlines():
 10             lline = lline.strip()
 11             if username == lline:
 12                 print("账号被锁")
 13                 flag = True
 14                 break
 15         if  flag == True:
 16             break
 17         #while True:
 18         u = open(‘name.txt‘,‘r‘)
 19         for uline in u.readlines():
 20             user,password,mony = uline.strip().split(‘:‘)
 21             #print(user)
 22 
 23             if username == user:
 24 
 25                 i = 0
 26                 while  i < 3:
 27                     passwd = input(‘Please enter a password:‘)
 28                     i +=1
 29 
 30                     if passwd == password:
 31                         print(‘欢迎%s登陆管理平台‘ % username)
 32                         flag = True
 33                         break
 34 
 35                     else:
 36                         if i >= 3:
 37                             with open(‘name_lock.txt‘,‘a‘) as l_2:
 38                                 l_2.write(username + ‘\n‘)
 39                             exit("试了太多次,将被锁定,请联系管理员")
 40                         print(‘密码输入错误,还有%d次机会‘ % (3 - i))
 41                 break
 42         else:
 43             print("用户输入错误,请重新输入")
 44         if flag == True:
 45             break
 46 
 47 def chazhao(backend):
 48     cz_list = []
 49     flag = False
 50     with open(‘ha.txt‘,‘r‘) as cz_1:                                        #打开旧配置文件
 51         for line in cz_1:
 52             cz_line = line.strip()
 53             if cz_line == "backend %s" % backend:                           #如果读取出的行等于输入的backend
 54                 flag = True
 55                 continue
 56             if flag == True and cz_line.startswith(‘backend‘):              #如果flag=True并且行开头为backend
 57                 break
 58             if flag == True and cz_line.startswith(‘server‘):               #如果flag= True并且行开头为server
 59                 cz_list.append(cz_line)
 60     return cz_list
 61 
 62 def add_1(dict_info):
 63     backend_title = dict_info.get(‘backend‘)
 64     crrent_title = "backend %s" %backend_title
 65     crrent_record = "server %s %s weight %s maxconn %s" %(dict_info[‘record‘][‘server‘], dict_info[‘record‘][‘server‘], dict_info[‘record‘][‘weight‘], dict_info[‘record‘][‘maxconn‘])
 66     cz_list = chazhao(backend_title)
 67     if cz_list:
 68         #backend存在
 69         if crrent_record in cz_list:    #如果新的数据在旧的配置文件中
 70             pass        #不操作
 71         else:           #否则,进行以下操作
 72             cz_list.append(crrent_record)    #插入数据
 73         #处理完成之后的中间部分
 74         #读取旧配置文件,写入新的配置文件中
 75         #边读边写
 76         #新处理后的配置文件写入新的配置文件中
 77         flag = False
 78         flag_1 = False
 79         with open(‘ha.txt‘,‘r‘) as ha_1,open(‘ha_new.txt‘,‘w‘) as ha_2:     #打开旧配置文件,打开新配置文件
 80             for line in ha_1:
 81                 if line.strip() == crrent_title:                                  #如果读取的行等于输入的backend
 82                     flag = True
 83                     ha_2.write(line)                                              #将读取的行写入新文件
 84                     continue                                                    #重新进行循环
 85                 if flag == True and line.startswith(‘backend‘):             #如果标志位等于True并且此行开头为‘backend’
 86                     flag = False                                                 #设置标志位为False(因为循环到了下一个‘backend’)
 87                 if flag == True and line.startswith(‘server‘):                #把已经处理完的数据,写入新配置文件中
 88                      if not flag_1:
 89                         for nwe_line in cz_list:
 90                             temp = ("\t"+nwe_line + "\n")
 91                             ha_2.write(temp.expandtabs())                         #将新的数据按行写入新配置文件中
 92                         flag_1 = True
 93                 else:
 94                     ha_2.write(line)
 95     else:
 96         #backend不存在,添加记录和backend
 97         with open(‘ha.txt‘,‘r‘) as ha_1,open(‘ha_new.txt‘,‘w‘) as ha_2:
 98             for line in ha_1:
 99                 ha_2.write(line)
100             ha_2.write("\n" + crrent_title + "\n")
101             temp = ("\t"+crrent_record + "\n")
102             ha_2.write(temp.expandtabs())
103     os.rename("ha.txt","ha.txt.back")                                   #将旧配置文件备份
104     os.rename("ha_new.txt","ha.txt")                                    #将新配置文件命名为线上使用的文件名
105     os.rename("ha.txt.back","ha_new.txt")
106 
107 def delt(dict_info):
108     backend_title = dict_info.get(‘backend‘)
109     crrent_title = "backend %s" %backend_title
110     crrent_record = "server %s %s weight %s maxconn %s" %(dict_info[‘record‘][‘server‘], dict_info[‘record‘][‘server‘], dict_info[‘record‘][‘weight‘], dict_info[‘record‘][‘maxconn‘])
111     cz_list = chazhao(backend_title)
112     if cz_list:                                         #如果列表有数据
113         if crrent_record in cz_list:       #如果数据在列表中
114             print(cz_list)
115             del cz_list[cz_list.index(crrent_record)]   #删除这个列表中找到的对应数据
116         print(cz_list)
117         with open(‘ha.txt‘,‘r‘) as ha_1,open(‘ha_new.txt‘,‘w‘) as ha_2:#打开新旧配置文件
118             flag = False
119             flag_1 = False
120             for line in ha_1:                                       #读取行在旧配置文件中
121                 line_strip = line.strip()                           #将读取的行前后空格删除
122                 if line_strip == crrent_title:                      #如果删除空格后的行数据等于输入的backend
123                     if len(cz_list)>0:                              #如果列表中还有数据
124                         ha_2.write(crrent_title + ‘\n‘)             #将backend写回去(前面删除的时候会把当前backend删除掉)
125                     flag = True
126                     continue                                        #跳出循环
127                 if flag == True and line_strip.startswith(‘backend‘):  #如果flag等于True并且行开头为backend
128                     flag = False
129                 if flag == True and line_strip.startswith(‘server‘):    #如果flag= True并且行开头为server执行下面步骤
130                     if not flag_1:
131                         for i in cz_list:
132                             temp = ("\t"+ i + "\n")
133                             ha_2.write(temp.expandtabs())
134                         flag_1 = True
135 
136                 else:
137                     ha_2.write(line)
138     else:
139         return
140     os.rename("ha.txt","ha.txt.back")
141     os.rename("ha_new.txt","ha.txt")
142     os.rename("ha.txt.back","ha_new.txt")
143 def main():
144     login()
145     while True:
146         print("1.查看 2.添加 3.删除 4.退出")
147         number = input("请输入序号:")
148 
149         if number == "1":
150             backend_1=input("请输入backend:")
151             cz = chazhao(backend_1)
152             print(cz)
153             continue
154         elif number == "2":
155             backend_1=input("请输入backend:")
156             server_1 = input("请输入server:")
157             weight_1 = input("请输入weight:")
158             maxconn_1 = input("请输入maxconn:")
159             s = ‘{"backend":"%s","record":{"server":"%s","weight":"%s","maxconn":"%s"}}‘%(backend_1,server_1,weight_1,maxconn_1)
160             data_dict = json.loads(s)
161             add_1(data_dict)
162             cz_1 = chazhao(backend_1)
163             print(cz_1)
164             continue
165         elif number == "3":
166             backend_1=input("请输入backend:")
167             cz = chazhao(backend_1)
168             print(cz)
169             server_1 = input("请输入server:")
170             weight_1 = input("请输入weight:")
171             maxconn_1 = input("请输入maxconn:")
172             s = ‘{"backend":"%s","record":{"server":"%s","weight":"%s","maxconn":"%s"}}‘%(backend_1,server_1,weight_1,maxconn_1)
173             data_dict = json.loads(s)
174             delt(data_dict)
175             cz_1 = chazhao(backend_1)
176             print(cz_1)
177             continue
178         elif number == "4":
179             exit()
180         else:
181             print("输入有误")
182             continue
183 if __name__ ==‘__main__‘:
184     main()
配置文件操作

python学习之配置文件查看,添加,删除配置程序(作业三)

标签:

原文地址:http://www.cnblogs.com/spykids/p/5180838.html

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