key 知识点:函数的定义, 函数的递归调用, flag 标志位的使用,eval() 函数

#!C:\Program Files\Python35\bin
# -*- conding:utf-8 -*-
# author: Frank def search_backend():
search_list=[] #定义一个空列表,存放所查到backend的信息
search_input = input("please input the backend which you want to search\n")
with open ('Haproxy.cfg') as f:
backend_flag = False #初始化标志位False
for line in f:
if line.strip()== 'backend %s'%search_input: #当匹配到所要查询的backend信息时,标志位为True,跳出本次循环,继续下一次循环
backend_flag = True
continue
if backend_flag and line.strip().startswith('backend'): #上一个if语句,将标志位置为True,当再次遇到以’backend‘ 开头时
#已经为下一个backend信息
break
if backend_flag and line.strip(): # 将上两个if条件除外的行追加到列表 search_list,即我们想要的行
search_list.append(line.strip())
if len(search_list) == 0:
print("\033[31;1m%s not exit, please re_input\033[0m"%search_input)
search_backend()
else:
for node in search_list: #打印列表的每一行
print(node) def add_backend():
args = '''{
'backend':'%s',
'record':{
'server':'%s',
'weight':'%s',
'maxconn':'%s'
}
}'''%(input('backend:'),input('server:'),input('weight:'),input('maxconn:'))
b = eval(args)
with open('Haproxy.cfg','a+',encoding='utf-8') as f:
#print(' ',file=f)
print('backend %s'%b['backend'],file=f,flush=True) #通过两个print, 将backend, 和下面的一行从格式上区别开
print('\t\tserver %s weight %s maxconn %s'%(b['record']['server'],b['record']['weight'],b['record']['maxconn']),file=f,flush=True) def delete_backend():
# 删除正好和查询的思路相反,search 是将结果追加到列表里, delete是将所要删除的排除在外
with open('Haproxy.cfg','r') as f_ori, open('Haproxy_new.cfg','a+') as f_new:
delete_input=input("please enter backend which you want to delete:")
backend_flag=True
for line in f_ori:
if line.strip() == 'backend %s'%delete_input:
backend_flag=False
continue
if line.strip().startswith('backend') and line.strip() != 'backend %s' %delete_input:
backend_flag=True
if backend_flag: #除删除之外的所有行写到一个新的文件里
f_new.write(line) Mesg = '''1. Search backend
2. Add backend
3. delete backend
4. quit
'''
while True:
print(Mesg)
user_input = input("please input which do you want:")
if user_input == "":
search_backend()
elif user_input == "":
add_backend()
elif user_input == "":
delete_backend()
elif user_input == '':
exit()
else:
exit(print("Invaild input ,exit"))
#执行结果
1. Search backend
2. Add backend
3. delete backend
4. quit please input which do you want:1
please input the backend which you want to search
www.baidu.com
server 10.22.23.45 weight 20 maxconn 30000
1. Search backend
2. Add backend
3. delete backend
4. quit please input which do you want:2
backend:www.google.cn
server:10.88.123.40
weight:20
maxconn:3400
1. Search backend
2. Add backend
3. delete backend
4. quit please input which do you want:4

定义三个函数

search_backend()

add_backend()

delete_backend()

对于add_backend() 和 delete_backend()函数都用到标志位(这里目前没有使用JSON)

1.如下文本信息,我要删除 www.baidu.com 所对应的信息, 采用for 循环和标志位的变换读出这两行信息

backend www.baidu.com
server 10.22.23.45 weight 20 maxconn 30000 backend buy.oldboy.org
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.93 100.1.7.93 weight 20 maxconn 300
search_list=[]
with open ('Haproxy.cfg') as f:
backend_flag = False #初始化标志位False
for line in f:
if line.strip()== 'backend www.baidu.com": #当匹配到所要查询的backend信息时,标志位为True,跳出本次循环,继续下一次循环
backend_flag = True
          search_list.append(line.strip("\n")
continue
if backend_flag and line.strip().startswith('backend'): #上一个if语句,将标志位置为True,当再次遇到以’backend‘ 开头时
#已经为下一个backend信息
break
if backend_flag and line.strip(): # 将上两个if条件除外的行追加到列表 search_list,即我们想要的行
search_list.append(line.strip())

2. search_backend() 使用函数的递归调用

    if len(search_list) == 0: #没有查询到结果
print("\033[31;1m%s not exit, please re_input\033[0m"%search_input)
search_backend()

3.eval()

eval 用法 : eval(expression,[globals=None,[locals=None]]

函数的作用:计算expression 的值,expression只能是单个运算表达式

  • expression: 必选参数,eval() arg 1 must be a string, bytes or code object, 如果expression 是一个string,会被当成一个python 表达式进行分析和解释, 正是本代码中用到的
>>> a = '''{
... 'backend':'www.baidu.com',
... 'record':{
... 'weight':'20',
... 'maxconn':'3400'
... }
... }'''
>>> a
"{\n\t 'backend':'www.baidu.com',\n\t 'record':{\n\t\t\t'weight':'20',\n\t\t\t 'maxconn':'3400'\n\t\t }\n }"
>>> eval(a)
{'record': {'weight': '', 'maxconn': ''}, 'backend': 'www.baidu.com'}
>>>
  • globals: optional 参数,表示全局命名空间,如果有,必须是一个字典对象
  • locals:   optional 参数,表示当前局部命名空间,可以是任意映射对象,如果省略,则与globals取相同的值
  • 如果globals 和 locals都省略,eval()取被调用环境下的命名空间的值

返回值

  如果expression是一个code对象,且创建该code对象时,complie函数的mode参数是“exec”,那么eval()函数返回值为None

  如果expression是一个输出语句,如print(),则eval()返回结果为None;

否则,expression表达式的结果就是eval()函数的返回值;

for instance:

>>> x=10
>>> y=20
>>> eval('x+y')
30
>>> eval('x+y',{'x':1,'y':2})
3
>>> eval('x+y',{'x':1,'y':2},{'y':3,'z':4})
4
>>> eval('print(x,y)')
10 20
>>> print(eval('print(x,y)'))
10 20
None

最新文章

  1. 细说SSO单点登录
  2. kibana 使用
  3. 菜鸟学Windows Phone 8开发(1)——创建第一个应用程序
  4. 【原创】深度神经网络(Deep Neural Network, DNN)
  5. (转载)研究openvswitch的流量模式
  6. simplexml 使用实例
  7. 神马是AB測试?
  8. Linux GIT服务器配置
  9. Educational Codeforces Round 15_C. Cellular Network
  10. Nginx负载均衡策略
  11. Backbone.js中的where和findWhere
  12. WP8.1小梦词典开发2:百度翻译API使用
  13. js的基本介绍
  14. ServletContext对象统计在线人数
  15. tween.js的使用
  16. 第二十一章 Django的分页与cookie
  17. [Luogu4705] 玩游戏
  18. 33.scrapy采集网站表单数据
  19. LeetCode 14 Longest Common Prefix(最长公共前缀)
  20. ps中的栅格化--引出--矢量图

热门文章

  1. sass判断语句
  2. Linux基础之-Bash命令优先级
  3. CentOS 7运维管理笔记(6)----Apache 基于 IP 的虚拟主机配置
  4. hiho一下 第一周 最长回文子串
  5. ArcGIS软件操作——地图配准
  6. C++模板详解(系转载,但是个人添加了一些内容)
  7. css outline属性
  8. 立即终止Sleep的线程
  9. C#连接SQL Server测试
  10. Java虚拟机3:内存溢出