python 多个脚本

1.增删改查haproxy.conf配置文件

1.查询输入:www.oldboy1.com

2.删除输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

3.增加输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

4.修改输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

 修改之后:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

 1 global
 2         log 127.0.0.1 local2
 3         daemon
 4         maxconn 256
 5         log 127.0.0.1 local2 info
 6 
 7 defaults
 8         log global
 9         mode http
10         timeout connect 5000ms
11         timeout client 50000ms
12         timeout server 50000ms
13         option  dontlognull
14 
15 listen  stats :8888
16         stats enable
17         stats uri       /admin
18         stats auth      admin:1234
19 
20 frontend oldboy.org
21          bind 0.0.0.0:80
22          option httplog
23          option httpclose
24          option  forwardfor
25          log global
26          acl www hdr_reg(host) -i www.oldboy.org
27          use_backend www.oldboy.org if www
28 
29 backend www.oldboy1.org
30         server 100.1.7.9 weight 20 maxconn 1111111
31         server 100.1.7.9 weight 20 maxconn 0
32         server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
33         server 10.10.10.1 10.10.10.1 weight 22   maxconn 2000
34         server 2.2.2.4 2.2.2.4       weight 20   maxconn 3000
35 
36 backend www.oldboy2.org
37         server 1.1.1.1 2.2.2.2 weight 20 maxconn 30
38         server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
39         server 10.10.10.1 10.10.10.1 weight 22   maxconn 2000
40 
41 backend www.oldboy20.org
42         server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
haproxy.conf配置文件
  1 import os
  2 
  3 
  4 def menu():
  5     menu = (
  6         """
  7         1. 增加
  8         2. 删除
  9         3. 修改
 10         4. 查找""")
 11     print(menu.lstrip('\n'))
 12 
 13 def InsertConf():
 14     content = eval(input("please input content:"))
 15     server1 = content["record"]["server"][0]
 16     server2 = content["record"]["server"][1]
 17     weight = content["record"]["weight"]
 18     maxconn = content["record"]["maxconn"]
 19     with open("hafile",mode="r",encoding="utf8") as f,open("hafile.bak",mode="w+",encoding="utf8") as f_bak:
 20         for line in f:
 21             if line.startswith("backend") and content["backend"] in line:
 22                 f_bak.write(line)
 23                 f_bak.write("        server %s %s weight %d maxconn %d\n" % (server1,server2, weight, maxconn))
 24                 continue
 25             f_bak.write(line)
 26         os.rename("hafile","hafile.obj")
 27         os.rename("hafile.bak","hafile")
 28 
 29 def DeleteConf():
 30     flag = False
 31     choice = eval(input("input content"))
 32     with open("hafile", encoding="utf8") as f_read, open("hafile.bak", mode="w", encoding="utf8") as f_write:
 33         for line in f_read:
 34             if line.startswith("backend") and choice["backend"] in line:
 35                 flag = True
 36             if choice["record"]["server"][0] in line \
 37                     and choice["record"]["server"][1] in line \
 38                     and str(choice["record"]["weight"]) in line \
 39                     and str(choice["record"]["maxconn"]) in line \
 40                     and flag == True:
 41                 flag = False
 42                 continue
 43             f_write.write(line)
 44         os.rename("hafile","hafile.obj")
 45         os.rename("hafile.bak","hafile")
 46 
 47 def UpdateConf():
 48     flag = False
 49     Original = eval(input("input Original content"))
 50     Modified = eval(input("input Modified content"))
 51     Modified = "\t\tserver %s %s weight %s maxconn %s\n" % (Modified["record"]["server"][0],\
 52                                                           Modified["record"]["server"][1], \
 53                                                           Modified["record"]["weight"], \
 54                                                           Modified["record"]["maxconn"])
 55     with open("hafile", encoding="utf8") as f_read, open("hafile.bak", mode="w", encoding="utf8") as f_write:
 56         for line in f_read:
 57             if line.startswith("backend") and Original["backend"] in line:
 58                 flag = True
 59                 print(line)
 60             if Original["record"]["server"][0] in line \
 61                     and Original["record"]["server"][1] in line \
 62                     and str(Original["record"]["weight"]) in line \
 63                     and str(Original["record"]["maxconn"]) in line \
 64                     and flag == True:
 65                 flag = False
 66                 f_write.write(Modified)
 67                 continue
 68             f_write.write(line)
 69 def FindConf():
 70     recode = []
 71     flag = False
 72     ipname = input("please input domain name:")
 73     with open("hafile",mode="r",encoding="utf8") as f:
 74         for line in f:
 75             if line.startswith("backend") and ipname in line:
 76                 flag = True
 77                 continue
 78             if line.startswith("backend")and flag == True:
 79                 break
 80             if flag:
 81                 recode.append(line.strip())
 82         for value in recode:
 83             print("\t%s"%(value.rstrip()))
 84 
 85 def Main():
 86     menu()
 87     choice = int(input("input number:"))
 88     return choice
 89 
 90 if __name__ == "__main__":
 91     while True:
 92         obj = Main()
 93         if obj == 1:
 94             InsertConf()
 95         elif obj ==2:
 96             DeleteConf()
 97         elif obj == 3:
 98             UpdateConf()
 99         elif obj == 4:
100             FindConf()
101         else:
102             continue
实现代码

 

2.用户认证

 用户输入账号密码三次错误,程序终止

 如果三次都是同一用户错误,锁定用户

1.定义一个字典,用户每次错误向字典增加记录{name count},当用户输入错误3次退出时,      判断字典的值是否大于3,大于3写到锁定文件里
1 alex      alex3417
2 oldboy    oldboy110
3 oldgirl   oldgirl110
账号 密码
 1 accounts = {}
 2 
 3 def lock_user(name):
 4     with open("lock_user", mode="r+", encoding="utf8") as f_lock:
 5         for line in f_lock:
 6             if line.strip().split()[0] == name:
 7                 print("Lock user")
 8                 exit()
 9 
10 def lockd_user(**kwargs):
11     with open("lock_user",mode="a+",encoding="utf8") as f_lockd_user:
12         for key in kwargs:
13             if kwargs[key] >2:
14                  f_lockd_user.write(key + "\n")
15 
16 
17 
18 
19 def check_user(name,passwd):
20     with open("user",mode="r",encoding="utf8") as f_check:
21         for line in f_check:
22             if name == line.strip().split()[0]:
23                 if passwd == line.strip().split()[1]:
24                     print("Success")
25                     exit()
26                 else:
27                     add_error(name)
28                     return name
29         return name
30 
31 def add_error(name):
32     if accounts:
33         if name in accounts:
34             accounts[name] += 1
35         else:
36             accounts[name] = 1
37     else:
38         accounts[name] = 1
39 
40 def main():
41     count = 0
42     while True:
43         name = input("input name: ")
44         passwd = input("input passwd: ")
45         lock_user(name)    #判断用户是否锁定
46         name = check_user(name,passwd)       #判断用户
47         count += 1
48         if count > 2:
49             lockd_user(**accounts)
50             print("exit than three")
51             break
52 
53 
54 if __name__ == '__main__':
55         main()
代码实现

 

1.猜年龄,最多输入三次

 1 count = 1
 2 age = 8
 3 while count <= 3:
 4     guess_age = int(input("please input your age: "))
 5     if guess_age == age:
 6         print("You're right")
 7         exit()
 8     elif count == 3:
 9         exit()
10     else:
11         print("try agin..")
12         count = count + 1
代码

 

2.猜年龄 ,每隔3次,问他一下,还想不想继续玩,y,n

 1 count = 1
 2 age = 18
 3 while True:
 4     guess_age = int(input("please input your age: "))
 5     if guess_age == age:
 6         print("You're right")
 7         exit()
 8     elif (count % 3) == 0:
 9         count += 1
10         play = input("do you want to paly{y|n}")
11         if play == "y":
12             continue
13         else:
14             exit()
15     else:
16         print("you're wrong")
17         count +=1
代码实现

 

3.编写登陆接口 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定

accounts = {}

def lock_user(name):
    with open("lock_user", mode="r+", encoding="utf8") as f_lock:
        for line in f_lock:
            if line.strip().split()[0] == name:
                print("Lock user")
                exit()

def lockd_user(**kwargs):
    with open("lock_user",mode="a+",encoding="utf8") as f_lockd_user:
        for key in kwargs:
            if kwargs[key] >2:
                 f_lockd_user.write(key + "\n")




def check_user(name,passwd):
    with open("user",mode="r",encoding="utf8") as f_check:
        for line in f_check:
            if name == line.strip().split()[0]:
                if passwd == line.strip().split()[1]:
                    print("Success")
                    exit()
                else:
                    add_error(name)
                    return name
        return name

def add_error(name):
    if accounts:
        if name in accounts:
            accounts[name] += 1
        else:
            accounts[name] = 1
    else:
        accounts[name] = 1

def main():
    count = 0
    while True:
        name = input("input name: ")
        passwd = input("input passwd: ")
        lock_user(name)    #判断用户是否锁定
        name = check_user(name,passwd)       #判断用户
        count += 1
        if count > 2:
            lockd_user(**accounts)
            print("exit than three")
            break


if __name__ == '__main__':
        main()
用户登录,三次后锁定

 

4.跳出3层循环

 1 flag = True
 2 
 3 while flag:
 4     while flag:
 5         while flag:
 6             if 1 != 2:
 7                 flag = False
 8                 
 9 
10 print("come on")
11 flag = False
12 
13 for i in range(10):
14 
15     print("爷爷好")
16 
17     for n in range(10):
18 
19         print("爸爸好")
20         
21         for k in range(10):
22 
23             print("孙子好")
24             if k == 2:
25                 flag = True
26                 break
27         if flag:
28             break
29     if flag:
30         break
31 
32 print("come on")
代码实现

 

5.购物车

 1 import os
 2 
 3 
 4 shop = ["Apple","coffee","book","condom"]
 5 price = [5800,30,50,90]
 6 shopping = []
 7 
 8 while True:
 9     try:
10         salary = int(input("input your salary: "))
11         break
12     except:
13         continue
14 
15 if salary <= min(price):
16     print("你工资太少了.金额为", salary, "退出吧..老表")
17     exit()
18 
19 
20 while True:
21     print("You can buy the following items")
22     for i in range(len(shop)):
23         print(i,".",shop[i],  " ",price[i])
24     choice = input("please choice number or input q exit>>").strip()
25     if choice.isdigit():
26         choice = int(choice)
27         if choice in range(len(shop)):
28             balance = salary - price[choice]
29             if balance >= 0:
30                 print("your bought",shop[choice],"balance",balance,"")
31                 shopping.append(shop[choice])
32                 salary = balance
33             else:
34                 print("you money",salary,"Differ",balance,"you can try")
35         else:
36             continue
37     elif choice == "q":
38         if len(shopping) == 0:
39             print("You didn't buy anything")
40         for i in range(len(shopping)):
41             print("You bought ",shopping[i])
42         print("Your balance:",salary)
43         break
44     else:
45         continue
代码实现
 1 import os
 2 
 3 
 4 shop = ["Apple","coffee","book","condom"]
 5 price = [5800,30,50,90]
 6 shopping = {}
 7 
 8 while True:
 9     try:
10         salary = int(input("input your salary: "))
11         break
12     except:
13         continue
14 
15 if salary <= min(price):
16     print("你工资太少了.金额为", salary, "退出吧..老表")
17     exit()
18 
19 count = 1
20 total = 0
21 while True:
22     print("You can buy the following items")
23     for i in range(len(shop)):
24         print("%s  %-6s  %d" % (i,shop[i],price[i]))
25     choice = input("please choice number or input q exit>>").strip()
26     if choice.isdigit():
27         choice = int(choice)
28         if choice in range(len(shop)):
29             balance = salary - price[choice]
30             if balance >= 0:
31                 print("\033[31;1myour bought\033[0m",shop[choice],"\033[31;1mbalance\033[0m",balance,"")
32                 if len(shopping) > 0:
33                     if shop[choice] in shopping.keys():
34                         shopping[shop[choice]][0] += 1
35                         shopping[shop[choice]][2] += price[choice]
36                     else:
37                         shopping[shop[choice]] = [1,price[choice],price[choice]]
38                 else:
39                     #print(shop[choice])
40                     shopping[shop[choice]] = [1,price[choice],price[choice]]
41                 salary = balance
42             else:
43                 print("you money",salary,"Differ",balance,"you can try")
44         else:
45             continue
46     elif choice == "q":
47         if len(shopping) == 0:
48             print("You didn't buy anything")
49         else:
50             print("id    商品    数量    单价    总价")
51             for i in shopping.keys():
52                 print("%-4d %-8s %-6d %-6d %-6d" % (count,i,shopping[i][0],shopping[i][1],shopping[i][2]))
53                 count += 1
54                 total += shopping[i][2]
55             print("\033[31;1myour balance\033[0m",total,"")
56             exit()
57     else:
58         continue
代码优化

 进度条

import sys,time
for i in range(101):
    s = "\r%d%% %s"%(i,"#"*i)
    sys.stdout.write(s)
    sys.stdout.flush()
    time.sleep(0.5)
进度条

 

6.打印三级菜单,省 市 县 

  可随时退出或跳出上一级

 1 menu = {
 2     '北京':{
 3         '海淀':{
 4             '五道口':{
 5                 'soho':{},
 6                 '网易':{},
 7                 'google':{}
 8             },
 9             '中关村':{
10                 '爱奇艺':{},
11                 '汽车之家':{},
12                 'youku':{},
13             },
14             '上地':{
15                 '百度':{},
16             },
17         },
18         '昌平':{
19             '沙河':{
20                 '老男孩':{},
21                 '北航':{},
22             },
23             '天通苑':{},
24             '回龙观':{},
25         },
26         '朝阳':{},
27         '东城':{},
28     },
29     '上海':{
30         '闵行':{
31             "人民广场":{
32                 '炸鸡店':{}
33             }
34         },
35         '闸北':{
36             '火车战':{
37                 '携程':{}
38             }
39         },
40         '浦东':{},
41     },
42     '山东':{},
43 }
菜单字典
 1 last_layer = []
 2 current_layer = menu
 3 
 4 
 5 while True:
 6     for i in current_layer:
 7         print(i)
 8     choice = input("please input layer or b:")
 9     if len(choice) == 0: continue
10     if choice in current_layer:
11         last_layer.append(current_layer)
12         current_layer = current_layer[choice]
13     if choice == "b":
14         if len(last_layer):
15             current_layer = last_layer[-1]
16             last_layer.pop()
17         else:
18             current_layer = menu
19     if choice == 'q':
20         break
代码实现
posted @ 2017-03-27 13:45  golangav  阅读(585)  评论(0编辑  收藏  举报