第一章

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 文件操作
  6. 字符编码与转码
  7. 函数编程,面向过程编程

sys模块

import sys

print(sys.path)  打印模块路径

print(sys.argv)  打印当前文件相对路径 ,与用户交互 如shell

中$1`$2

与或关系

or    或
and 和
not  否
in    是否存在
not in

is
type(a) is list   判断是不是列表

&   与
|    或

^   两个为真才为真

>>    先向右移
<<    向左移

运算

8 ** 2        次方
3 + 2         加
16 - 8        减
8 * 8         乘
8 / 2         除
100 // 50    求整除
100 % 50    取模

列表

name = ["zhang","li","wang","liu"]

print(name[-3:])              切片倒数3个

name.append("han")         添加
name.insert(2,"hanwei")    插入
name[2] = "99999"           修改
name.remove("zhang")      删除
del name[1]                     删除
name.pop(1)                    删除
name.sort()                      排序
name.reverse()                 反向排序
name.clear()                    清除
print(name.index("wang")) 打印下标
print(name.count("liu"))    取总数

浅copy 

name = ["zhangsan","lisi",["ai","ni"],"wangermazi","liuliu"]
name2 = name.copy()
name[1] = "wangwu"
name[2][0] = "aa"
print(name)
print(name2)

深copy

import copy
name = ["zhangsan","lisi",["ai","ni"],"wangermazi","liuliu"]
name2 = copy.deepcopy(name)
name[0] = "zhang"
name[2][0] = "vv"
print(name)
print(name2)

循环打印列表

for i in name:
print(i)

不常切片列表
print(name[::2])

元组和列表的区别在于不可以删改 
元组又叫只读列表

三元运算

a,b,c = 2,4,6

print(5) if a < b else print(444)

购物车练习

 1 #/usr/bin/python env
 2 # -*-  encoding:utf8 -*-
 3 
 4 sc_list = [
 5     ('iphone7',7999),
 6     ('tesla',1000000),
 7     ('bike',800),
 8     ('coffee',50),
 9     ('MAC',9000),
10 ]
11 
12 salary = input("33[35m请输入你的金额:33[0m")
13 user_sp = []
14 if salary.isdigit():
15     salary = int(salary)
16     while True:
17         for index,time in enumerate(sc_list):
18             print(index,time)
19         user_gw = input("33[35m请选择你要购买的商品:33[0m")
20         if user_gw.isdigit():
21             user_gw = int(user_gw)
22             if user_gw <= len(sc_list) and user_gw >= 0:
23                 t_time = sc_list[user_gw]
24                 if salary >= t_time[1]:
25                     salary -= t_time[1]
26                     user_sp.append(t_time)
27                 else:
28                     print("33[35m你的%s不足!33[0m"%salary)
29             else:
30                 print("33[35m你输入的商品不存在!33[0m")
31         elif user_gw == 'q':
32             print("33[36m你的剩余余额为:%s33[0m" % salary)
33             for i in user_sp:
34                 print(i)
35             exit('quit')
36         else:
37             print('33[34m输入错误!33[0m')
View Code
 1 import time
 2 
 3 time1 = '%Y-%m-%d:%X'
 4 mtiem = time.strftime(time1)
 5 
 6 sc_list = [
 7     ('iphone7',7999),
 8     ('tesla',1000000),
 9     ('bike',800),
10     ('coffee',50),
11     ('MAC',9000),
12 ]
13 
14 a= open("mn.txt","r").readline()
15 salary = int(a)
16 
17 user_sp = []
18 # if salary.isdigit():
19 #     salary = int(salary)
20 while True:
21     for index, time in enumerate(sc_list):
22         print(index, time)
23     user_gw = input("33[35m请选择你要购买的商品:33[0m")
24     if user_gw.isdigit():
25         user_gw = int(user_gw)
26         if user_gw <= len(sc_list) and user_gw >= 0:
27             t_time = sc_list[user_gw]
28             if salary >= t_time[1]:
29                 salary -= t_time[1]
30                 user_sp.append(t_time)
31                 with open("mn.txt", "w")as f1, 
32                         open("sp.txt", "a+")as f2:
33                     f1.write(str(salary))
34                     #f1.write("-->%s
" % mtiem)
35                     f2.write(str(user_sp))
36                     f2.write("-->%s
" % mtiem)
37             else:
38                 print("33[35m你的%s不足!33[0m" % salary)
39         else:
40             print("33[35m你输入的商品不存在!33[0m")
41     elif user_gw == 'q':
42 
43         with open("sp.txt","r") as f1:
44             for t in f1:
45               print(t)
46         print("33[36m你的剩余余额为:%s33[0m" % salary)
47         exit("quit")
48     else:
49         print('33[34m输入错误!33[0m')
View Code

字典

info = {'stu1101': "tengkan wu",
'stu1102':"longze luola",
'stu1103':"xiaoze maliya",
}

增加

存在修改不存在添加

1 info["stu1104"] = "苍井空"
View Code

修改

1 info["stu1101"] ="武藤兰"
View Code

删除

1 info.pop("stu1101")
2 del info["stu1102"]
3 info.popitem()
View Code

查找不存在会报错

1 print(info['stu1101'])
View Code

查找不存在不会报错

1 print(info.get('stu1101')
View Code

嵌套字典

 1 av_catalog = {
 2     "欧美":{
 3         "www.youprn.com":["很多免费的,世界最大的","质量一般"],
 4         "www.pornhub.com":["很多免费的,也很大","质量比yourporn高点"],
 5         "letmedothistoyou.com":["多是自拍,高质量图片很多","资源不多,更新慢"],
 6         "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
 7     },
 8     "日韩":{
 9         "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"],
10           },
11     "大陆":{
12         "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
13     }
14 }
View Code

追加操作

1 av_catalog["大陆"]["1024"][1] += "可以用爬虫爬下来"
View Code

打印keys,values

1 print(info.values())
2 print(info.keys())
View Code

添加,不存在添加,存在不做任何操作

1 info.setdefault("stu1106",'alex')
2 info.setdefault("stu1102","泷泽萝拉")
View Code

更新

1 b = {1:2,3:4,'stu1102':"泷泽萝拉"}
2 info.update(b)
View Code

将字典转为列表

1 print(info.items())
View Code


这是个坑少用
dict.fromkeys([1,2,3],'testd')
{1: 'testd', 2: 'testd', 3: 'testd'}

循环打印字典

1 for key in info:
2      print(key,info[key])
3 
4 
5 for k,v in info.items():
6      print(k,v)
View Code

三级菜单

1.定义字典

2.循环打印

3.让用户选择

4.循环,判断用输入的是否是数字
4.1.判断长度不可以大于字典的长度
4.2.如果用户输入的是q退出
4.3.取出用户的选择并且转换成列表

5.继续循环,判断用输入的是否是数字
5.1.判断长度不可以大于字典的长度
4.2.如果用户输入的是q退出
4.3.如果用户输入的是b退出
4.3.取出用户的选择并且转换成列表

6.继续循环,判断用输入的是否是数字
6.1.打印最后一页
6.2.如果用户输入的是q退出
6.3.如果用户输入的是b退出

 1 #!/usr/bin/python env
 2 # -*- encoding:utf-8 -*-
 3 name = {
 4     "香港":{
 5         "音乐":{
 6             "男歌手":["陈奕迅","张学友","王杰","郭富城"],
 7             "女歌手":["王菲","梁咏琪","甄妮","陈慧琳"]
 8         },
 9         "影视":{
10             "男演员":["刘德华","谢霆锋","成龙","周瑞发"],
11             "女演员":["张曼玉","叶玉卿","邱淑贞","温碧霞"]
12         }
13     },
14     "大陆":{
15         "音乐":{
16             "男歌手":["阿木","安琥","陈少华","戴军"],
17             "女歌手":["田震","韩晶","郭美美","王蓉"]
18         },
19         "影视":{
20             "男演员":["马天宇","蒋劲夫","陈学冬","李易峰"],
21             "女演员":["杨颖","唐嫣","杨幂","张馨予"]
22         }
23     }
24 }
25 
26 
27 
28 flag = True
29 
30 while flag:
31     for i,k in enumerate(name):
32         print(i,k)
33     user_1 = input('请输入第一级菜单,q,退出:')
34     if user_1 == 'q':
35         flag = True
36         break
37     if user_1.isdigit():
38         user_1 = int(user_1)
39         if user_1 <= len(name):
40             key_1 = list(name.keys())[user_1]
41             while flag:
42                 for i,k in enumerate(name[key_1]):
43                     print(i,k)
44                 user_2 = input("请选择第二级菜单,q.退出,b.返回:")
45                 if user_2 == 'q':
46                     flag = False
47                     break
48                 if user_2 == 'b':
49                     break
50                 if user_2.isdigit():
51                     user_2 = int(user_2)
52                     if user_2 <= len(name[key_1]):
53                         key_2 = list(name[key_1].keys())[user_2]
54                         while flag:
55                             for i,k in enumerate(name[key_1][key_2]):
56                                 print(i,k)
57                             user_3 = input("请选择三级菜单,q.退出,b返回:")
58                             if user_3 == 'q':
59                                 flag = False
60                                 break
61                             if user_3  == 'b':
62                                 break
63                             if user_3.isdigit():
64                                 user_3 = int(user_3)
65                                 if user_3 <= len(name[key_1][key_2]):
66                                     key_3 = list(name[key_1][key_2].keys())[user_3]
67                                     while flag:
68                                         for i,k in enumerate(name[key_1][key_2][key_3]):
69                                             print(i,k)
70                                         user_4 = input("最后一页,q.退出,b.返回:")
71                                         if user_4 == 'q':
72                                             flag =False
73                                             break
74                                         if user_4 == 'b':
75                                             break
View Code

 集合

集合特点无序不重复

a = [1,3,5,7,9]
b = [2,3,6,8,10]
a1 = set(a)
b2 = set(b)

c1 = [11,22,33,44]
c2 = [55,66,77,11,22]
c = set(c1)
d = set(c2)

difference(差集)

1 print(a1.difference(b2))
View Code

difference_update(差集更新)

把差集更新到a1

1 print(a1.difference_update(b2))
View Code

symmetric_difference(取两个集合的差集)

1 print(c.symmetric_difference(d))
View Code

sysmmetric_difference_update(把两个集合的差集更新到c)

1 c.symmetric_difference_update(d))
2 print(c)
View Code

intersection(交集)

1 print(d.intersection(c))
View Code

intersection_update(交集更新)

把d和c的交集更新到d

1 d.intersection_update(c)
2 print(d)
View Code

isdisjoint(判断是否有交集)

有返回False没没有返回True

1 print(c.isdisjoint(d))
View Code

union(并集,合并去重)

1 print(c.union(d))
View Code

issubset(判断子集)

是返回True,否返回False

1 print(d.issubset(c))
View Code

issuperset(判断父集)

是返回Ture,否返回False

1 print(c.issuperset(d))
View Code

add(添加)

一次只能添加一个

1 a1.add("alex")
View Code

update(更新)

一次可以添加多个

1 a1.update("a","b")
View Code

clear(清空)

1 a1.clear()
View Code

删除

1 a1.discard(1)    不存在不报错
2 
3 c.pop()              随机删除
4 
5 c.remove(123)  删除如果不存在报错
View Code

文件操作

r 读
w 写,会新建一个文件
r + 读写
w + 写读

b 二进制
rb
wb
r + b
w + b

指定编码打开文件

1 f = open("yesterday2", 'w+', encoding="utf-8")
2 f.write('-----------diao2-------------1
')
3 
4 f = open("yesterday2", 'wb'   二进制的方式打开
View Code

读取文件打印前九行

1 f = open('b.txt', 'r')
2 count = 0
3 for line in f:
4     if count == 9:
5         break
6     print(line)
7     count += 1
View Code

readline()

一行一行的读

1 print(f.readlne())
View Code

readlines()

把所有内容读成一行

1 print(f.readlines())
View Code

tell()

打印指针

1 print(f.tell())
View Code

seek()

移动指针

1 print(f.seek(0))
View Code

flush()

刷新

1 f.flush()
View Code

close()

关闭文件

1 f.close()
View Code

滚动条

1 import sys,time
2 
3 for i in range(20):
4      sys.stdout.wrtie("%:",)
5      sys.stdout.flush()
6      time.sleep(0.1)
View Code

修改文件

 1 1.
 2 import sys, time
 3 
 4 f = open("yesterday2", 'r', encoding='utf-8')
 5 f_new = open("yy", 'w', encoding="utf-8")
 6 
 7 for line in f:
 8     if "肆意的快乐等我享受" in line:
 9         line = line.replace("肆意的快乐等我享受", "肆意的快乐等alex享受")
10         f_new.write(line)
11     else:
12         f_new.write(line)
13 f.close()
14 f_new.flush()
15 f_new.close()
16 
17 
18 2.
19 
20 find_str = sys.argv[1]
21 用户交互
22 reaplace_str = sys.argv[2]
23 用户交互
24 
25 
26 import sys, time
27 
28 f = open("yesterday2", 'r', encoding='utf-8')
29 f_new = open("yy", 'w', encoding="utf-8")
30 
31 for line in f:
32     if find_str in line:
33         line = line.replace(find_str,reaplace_str )
34         f_new.write(line)
35     else:
36         f_new.write(line)
37 f.close()
38 f_new.flush()
39 f_new.close()
View Code

with

打开文件免关闭

1 with open("a.txt","r",encoding="utf-8") as f ,
2      open ("b.txt","r",encoding="utf-8")as f2:
3     for i in f:
4         print(i)
View Code

字符编码与转码

1.ascii - Unicode - utf8 - gbk     转码流程 先有转为 Unicode 再有Unicode转为utf8或者gbk
2.ascii 站一个字节,Unicode站两个字节,utf8,站三个字节
3.一个字节八个bit


python2(转码)
 1 python2 默认是ascii
 2 
 3 /usr/bin/python env
 4 -*- encoding:utf-8 -*-
 5 python2
 6 import sys
 7 print(sys.getdefaultencoding())                          查看默认字符编码
 8 a = "你好"
 9 a_to_gbk = a.decode("utf8").encode("gbk")                  转 gbk
10 a_to_utf8 = a_to_gbk.decode("gbk").encode("utf8")     转 utf8
11 
12 print(a_to_utf8)
View Code
python3(转码)
 1 python3 默认是utf8
 2 python3 转gbk
 3 
 4 #/usr/bin/python env
 5 #-*- encoding:utf-8 -*-
 6 
 7 import sys
 8 print(sys.getdefaultencoding())
 9 a = "你好"
10 a_to_gbk = a.encode("gbk")
11 
12 print(a_to_gbk)
13 
14 
15 
16 
17 python3 转utf8
18 
19 #/usr/bin/python env
20 #-*- encoding:gbk -*-
21 
22 import sys
23 print(sys.getdefaultencoding())
24 a = "你好"
25 a_to_gbk = a.encode("utf8")
26 print(a_to_gbk)
27 
28 print(a.encode("gb2312"))            转gb2312
View Code

函数编程,面向过程编程

函数特点减少重复代码 可扩展

时间模块

1 import time
2 def logger():
3     time_format = '%Y-%m-%d %X'
4     time_current = time.strftime(time_format)
5     with open("a.txt","a+")as f:
6         f.write("%s sdfsdf
"% time_current)
View Code

固定实参和不固定实参

 1 def test(x,y,z):   形参
 2     print(x)
 3     print(y)
 4     print(z)
 5 
 6 
 7 test(3,z=1,y=5)   实参  
 8 
 9 
10 3      固定实参 
11 
12 z=1 不固定 实参 
*args(可以接受多个固定实参)
1 def test(hh,*args):
2     print(args)
3     print(hh)
4 
5 test("w",1,2,3,4,5)

默认参数

1 test(3,z=1,y=5)
2 def test(hh,*args):
3     print(args)
4     print(hh)
5 
6 
7 z=1,y=5 默认参数,可以不用传实参
**kwargs(参数组,可以接受多个不固定实参)
 1 def test4(name,age=18,**kwargs):
 2     print(name)
 3     print(age)
 4     print(kwargs)
 5 
 6 test4("alex",sex="m",hobby="test")
 7 
 8 
 9 alex
10 18
11 {'sex': 'm', 'hobby': 'test'}
 1 def test4(name,age=18,**kwargs):
 2     print(name)
 3     print(age)
 4     print(kwargs)
 5 
 6 test4("alex",sex="m",hobby="test",age=888)
 7 
 8 
 9 
10 alex
11 888
12 {'sex': 'm', 'hobby': 'test'}
如果不给*args传实参会是一个空元组
 1 def test4(name,age=18,*args,**kwargs):
 2     print(name)
 3     print(age)
 4     print(args)
 5     print(kwargs)
 6 
 7 test4("alex",age=34,sex="m",hobby="test")
 8 
 9 
10 alex
11 34
12 ()
13 {'sex': 'm', 'hobby': 'test'}

面向过程

1 def test():              面向过程可以判断return返回值进行下一步的判断
2     print(123)
3     return 0
4 
5 a = test()
6 print(a)
7 
8 123
9 0

 局部变量与全局变量

1.全局变量,在文件开头,在整个文件生效。

2.局部变量,只在函数内生效。

3.局部变量,不可以修改全局变量的字符串和整数,但是可以修改列表和字典。

global

可以修改全局变量,切记勿用!

school = "oldboy"

def change_name(name):
    global school
    school= "Mage Linux"
    print(school)


change_name()
print(school)

   函数内修改全局列表

name = ["alex","jack","rain"]

def change_name():
      name[0] = "金角大王"

change_name()
print(name)

  递归

1.递归要有条件结束,每递归一次会多一个站,每递归一次需要减少一次递归的条件。

2.递归是指函数自己在调用自己。

def calc(n):
    print(n)
    if int(n / 2) > 0:
        return calc(int(n/2))
    print("----->",n)                                   最后结果是1因为最后相除得1不满足条件

calc(10)

  高阶函数

1.高阶函数是函数调用另一个函数,如abs或自己写的函数。

def add(a,b,f):
    return f(a)+f(b)

ret = add(6,-3,abs)
print(ret)

  proxy.conf文件操作

执行程序按下列操作

1.查询  
 ww.oldboy.org

2.删除或添加 
 {'backend':'ww.oldboy.org','record':{'server':'1.1.1.123','weight':'2','maxconn':'200'}}

3.修改
 [{'backend':'ww.oldboy.org','record':{'server':'100.1.7.9','weight':'20','maxconn':'30'}},{'backend':'ww.oldboy.org','record':{'server':'100.1.7.10','weight':'10','maxconn':'33'}}]

  

  1 #/usr/bin/python env
  2 # -*- encoding:gbk -*-
  3 
  4 import os
  5 
  6 def fetch(data):
  7     backend_data = "backend %s" % data
  8     r_list = []
  9     with open("haproxy.conf", "r")as f:
 10         tag = False
 11         for line in f:
 12             if line.strip() == backend_data:
 13                 tag = True
 14                 continue
 15             if tag and line.startswith('backend'):
 16                 break
 17             if tag and line:
 18                 r_list.append(line.strip())
 19     for i in r_list:
 20         print(i)
 21     return r_list
 22 
 23 
 24 def add(data):
 25     backend = data['backend']
 26     record_list = fetch(backend)
 27     backend_data2 = 'server %s %s weight %s maxconn %s ' % (data['record']['server'],
 28                                                             data['record']['server'],
 29                                                             data['record']['weight'],
 30                                                             data['record']['maxconn'])
 31 
 32     backend_data = 'backend %s' % backend
 33 
 34     if not record_list:
 35         record_list.append(backend_data)
 36         record_list.append(backend_data2)
 37 
 38         with open("haproxy.conf", "r") as f, 
 39                 open("haproxy_new.conf", "w") as f2:
 40             for line in f:
 41                 f2.write(line)
 42 
 43             for l in record_list:
 44                 if l.startswith('backend'):
 45                     f2.write(l +'
')
 46                 else:
 47                     f2.write("%s%s
" % (' ' * 8, l))
 48 
 49         os.rename("haproxy.conf", "haproxy_bak.conf")
 50         os.rename("haproxy_new.conf", "haproxy.conf")
 51         os.remove("haproxy_bak.conf")
 52     else:
 53         record_list.insert(0, backend_data)
 54         if backend_data2 not in record_list:
 55             record_list.append(backend_data2)
 56             with open('haproxy.conf', 'r') as f,
 57                     open('haproxy_new.conf', 'w') as f2:
 58                 tag = False
 59                 tag2 = False
 60                 for line in f:
 61                     if line.strip() == backend_data:
 62                         tag = True
 63                         continue
 64                     if tag and "backend" in line:
 65                         tag = False
 66                     if not tag:
 67                         f2.write(line)
 68                     else:
 69                         if not tag2:
 70                             for lines in record_list:
 71                                 if "backend" in lines:
 72                                     f2.write(lines + '
')
 73                                 else:
 74                                     f2.write('%s%s
' % (' ' * 8, lines))
 75                             tag2 = True
 76 
 77             os.rename('haproxy.conf', 'haproxy_bak.conf')
 78             os.rename('haproxy_new.conf', 'haproxy.conf')
 79             os.remove('haproxy_bak.conf')
 80 
 81 
 82 def remove(data):
 83     backend = data['backend']
 84     record_list = fetch(backend)
 85     backend_data2 = "server %s %s weight %s maxconn %s" %(data['record']['server'],
 86                                                           data['record']['server'],
 87                                                           data['record']['weight'],
 88                                                           data['record']['maxconn'])
 89 
 90     backend_data = 'backend %s' % backend
 91 
 92     if not record_list or backend_data2 not in record_list:
 93         print("数据不存在:!")
 94         return
 95 
 96     else:
 97         record_list.insert(0,backend_data)
 98         record_list.remove(backend_data2)
 99 
100         with open('haproxy.conf', 'r') as f, 
101                 open('haproxy_new.conf', 'w') as f2:
102             tag = False
103             tag2 = False
104             for line in f:
105                 if line.strip() == backend_data:
106                     tag = True
107                     continue
108                 if tag and "backend" in line:
109                     tag = False
110                 if not tag:
111                     f2.write(line)
112                 else:
113                     if not tag2:
114                         for lines in record_list:
115                             if "backend" in lines:
116                                 f2.write(lines + '
')
117                             else:
118                                 f2.write('%s%s
' % (' ' * 8, lines))
119                         tag2 = True
120 
121         os.rename('haproxy.conf', 'haproxy_bak.conf')
122         os.rename('haproxy_new.conf', 'haproxy.conf')
123         os.remove('haproxy_bak.conf')
124 
125 
126 def change(data):
127     backend = data[0]['backend']
128     record_list = fetch(backend)
129     backend_data = "backend %s" % backend
130     old_data = "server %s %s weight %s maxconn %s" %(data[0]['record']['server'],
131                                                         data[0]['record']['server'],
132                                                         data[0]['record']['weight'],
133                                                         data[0]['record']['maxconn'],)
134 
135     new_data = "server %s %s weight %s maxconn %s" %(data[1]['record']['server'],
136                                                         data[1]['record']['server'],
137                                                         data[1]['record']['weight'],
138                                                         data[1]['record']['maxconn'],)
139     if not record_list or old_data not in record_list:
140         print("没有记录:!")
141         return
142     else:
143         record_list.insert(0, backend_data)
144         index = record_list.index(old_data)
145         record_list[index] = new_data
146 
147         with open('haproxy.conf', 'r') as f, 
148                 open('haproxy_new.conf', 'w') as f2:
149             tag = False
150             tag2 = False
151             for line in f:
152                 if line.strip() == backend_data:
153                     tag = True
154                     continue
155                 if tag and "backend" in line:
156                     tag = False
157                 if not tag:
158                     f2.write(line)
159                 else:
160                     if not tag2:
161                         for lines in record_list:
162                             if "backend" in lines:
163                                 f2.write(lines + '
')
164                             else:
165                                 f2.write('%s%s
' % (' ' * 8, lines))
166                         tag2 = True
167 
168         os.rename('haproxy.conf', 'haproxy_bak.conf')
169         os.rename('haproxy_new.conf', 'haproxy.conf')
170         os.remove('haproxy_bak.conf')
171 
172 
173 if __name__ == '__main__':
174     msg = '''
175     1:查询
176     2:添加
177     3:删除
178     4:修改
179     5:exit
180     '''
181 
182     menu_dict = {
183         '1': fetch,
184         '2': add,
185         '3': remove,
186         '4': change,
187         '5': exit
188     }
189 
190 while True:
191     print(msg)
192     choice = input("操作>>:").strip()
193     if len(choice) == 0 or choice not in menu_dict: continue
194     if choice == '5': break
195     data = input("数据>>:")
196     if choice != '1':
197         data = eval(data)
198     menu_dict[choice](data)
View Code

优化后

  1 #!/usr/bin/python env
  2 # -*- coding:utf-8 -*-
  3 import os
  4 
  5 def file_handel(filename,backend_data,record_list=None,type='fetch'):
  6     new_file='new_'+ filename
  7     back_file=filename+'_bak'
  8     r_list = []
  9 
 10     if type == 'fetch':
 11         with open(filename,"r")as f:
 12             tag = False
 13             for line in f:
 14                 if line.strip() == backend_data:
 15                     tag = True
 16                     continue
 17                 if tag and line.startswith('backend'):
 18                     break
 19                 if tag and line:
 20                     r_list.append(line.strip())
 21         for i in r_list:
 22             print(i)
 23         return r_list
 24 
 25     if type == 'appen':
 26         with open(filename, "r") as f, 
 27                 open(new_file, "w") as f2:
 28             for line in f:
 29                 f2.write(line)
 30 
 31             for l in record_list:
 32                 if l.startswith('backend'):
 33                     f2.write(l +'
')
 34                 else:
 35                     f2.write("%s%s
" % (' ' * 8, l))
 36 
 37         os.rename(filename,back_file)
 38         os.rename(new_file,filename)
 39         os.remove(back_file)
 40 
 41 
 42     if type == 'change':
 43         with open(filename,'r') as f, 
 44                 open(new_file,'w') as f2:
 45             tag = False
 46             tag2 = False
 47             for line in f:
 48                 if line.strip() == backend_data:
 49                     tag = True
 50                     continue
 51                 if tag and "backend" in line:
 52                     tag = False
 53                 if not tag:
 54                     f2.write(line)
 55                 else:
 56                     if not tag2:
 57                         for lines in record_list:
 58                             if "backend" in lines:
 59                                 f2.write(lines + '
')
 60                             else:
 61                                 f2.write('%s%s
' % (' ' * 8, lines))
 62                         tag2 = True
 63 
 64         os.rename(filename,back_file)
 65         os.rename(new_file,filename)
 66         os.remove(back_file)
 67 
 68 
 69 
 70 
 71 
 72 
 73 def fetch(data):
 74     backend_data = "backend %s" % data
 75     return file_handel("haproxy.conf",backend_data,type='fetch')
 76 
 77 def add(data):
 78     backend = data['backend']
 79     record_list = fetch(backend)
 80     backend_data2 = 'server %s %s weight %s maxconn %s ' % (data['record']['server'],
 81                                                             data['record']['server'],
 82                                                             data['record']['weight'],
 83                                                             data['record']['maxconn'])
 84 
 85     backend_data ="backend %s" % backend
 86 
 87     if not record_list:
 88         record_list.append(backend_data)
 89         record_list.append(backend_data2)
 90         file_handel('haproxy.conf',backend_data,record_list,type='appen')
 91 
 92     else:
 93         record_list.insert(0, backend_data)
 94         if backend_data2 not in record_list:
 95             record_list.append(backend_data2)
 96             file_handel('haproxy.conf',backend_data,record_list,type='change')
 97 
 98 
 99 
100 def remove(data):
101     backend = data['backend']
102     record_list = fetch(backend)
103     backend_data2 = "server %s %s weight %s maxconn %s" %(data['record']['server'],
104                                                           data['record']['server'],
105                                                           data['record']['weight'],
106                                                           data['record']['maxconn'])
107 
108     backend_data = 'backend %s' % backend
109 
110     if not record_list or backend_data2 not in record_list:
111         print("数据不存在:!")
112         return
113 
114     else:
115         record_list.insert(0,backend_data)
116         record_list.remove(backend_data2)
117         file_handel('haproxy.conf', backend_data, record_list, type='change')
118 
119 def change(data):
120     backend = data[0]['backend']
121     record_list = fetch(backend)
122     backend_data = "backend %s" % backend
123     old_data = "server %s %s weight %s maxconn %s" %(data[0]['record']['server'],
124                                                         data[0]['record']['server'],
125                                                         data[0]['record']['weight'],
126                                                         data[0]['record']['maxconn'],)
127 
128     new_data = "server %s %s weight %s maxconn %s" %(data[1]['record']['server'],
129                                                         data[1]['record']['server'],
130                                                         data[1]['record']['weight'],
131                                                         data[1]['record']['maxconn'],)
132     if not record_list or old_data not in record_list:
133         print("没有记录:!")
134         return
135     else:
136         record_list.insert(0, backend_data)
137         index = record_list.index(old_data)
138         record_list[index] = new_data
139 
140         file_handel('haproxy.conf', backend_data, record_list, type='change')
141 
142 if __name__ == '__main__':
143     msg = '''
144     1:查询
145     2:添加
146     3:删除
147     4:修改
148     5:exit
149     '''
150 
151     menu_dict = {
152         '1': fetch,
153         '2': add,
154         '3': remove,
155         '4': change,
156         '5': exit
157     }
158 
159 while True:
160     print(msg)
161     choice = input("操作>>:").strip()
162     if len(choice) == 0 or choice not in menu_dict: continue
163     if choice == '5': break
164     data = input("数据>>:")
165     if choice != '1':
166         data = eval(data)
167     menu_dict[choice](data)
View Code
原文地址:https://www.cnblogs.com/hanwei999/p/6580272.html