python自学第三周haproxy练习题未完待续

__author__ = 'Administrator'


import fileinput
#!/usr/bin/env python

# -*-coding:UTF-8-*-

import io,sys

def numif(number): # 判断输入是否为数字

    while not number.isdigit():    # 输入不是数字就进入循环

        number = input('\033[31m 输入%s不是数字,请重新输入!\033[0m' % number)    # 提示重新输入

    number = number

    return number

def chioce():

            print('--------------请选择-----------------')

            print('1、添加backwend和server信息')

            print('2、修改backwend和server信息')

            print('3、删除backwend和server信息')

            print('4、查询backwend和server信息')

            print('5、退出')

            print('------------------------------------')

           # number = numif(input("请选择您的操作:"))

            number=input("请选择您的操作:")

            return number



def add():

        new={}#新增

        new["backend"]=input( '请输入bakend:')

        new["server"]=input('请输入recordserver:')

        new["IP"]=input('请输入IP:')

        new["weight"]=input('请输入recordweight:')

        new["maxconn"]=input('请输入recordmaxconn:')

        all= 'backend  %(backend)s \n        server %(server)s %(IP)s weight %(weight)s maxconn %(maxconn)s' % new

       #格式化输出字典

        with open('E:\haproxy.txt','a') as f_new:

            f_new.write(all)


def lineno():

    fro = open('E:\haproxy.txt', "r")
    frw = open('E:\haproxy.txt', "r+")
    current_line = 0
    strinput=input('请输入需要删除的信息:')
    for line in fro:

      current_line+=1

      if line.startswith(strinput):#只与开始进行匹配

          break
    fro.close()
    frw.close()
    return current_line #返回需要删除的字符所在行的行号

def removeLine(filename, lineno):
    fro = open(filename, "r")

    current_line = 0
    while current_line < lineno:
        fro.readline()
        current_line += 1

    seekpoint = fro.tell()#需要被删除的位置,读对应的指针
    frw = open(filename, "r+")
    frw.seek(seekpoint, 0)#定位到删除位置

    # read the line we want to discard
    fro.readline()  # 读入一行进内内存 同时! 文件指针下移实现删除

    # now move the rest of the lines in the file
    # one line back
    chars = fro.readline()
    while chars:
        frw.writelines(chars)
        chars = fro.readline()

    fro.close()
    frw.truncate()
    frw.close()
    
    
    
def search(arg):
    fro = open('E:\haproxy.txt', "r")
    flag=False
    result=[]
    for line in fro:

        if line.startswith(arg):
            flag=True
            continue
        if line.startswith("backend"):
            flag=False
        if flag:

            result.append(line)
    return result


while True:

    number=chioce()

    if number=='1':

       add()

    if number=='2':

        print('修改')

    if number=='3':

        removeLine('E:\haproxy.txt', lineno()-1)

    if number=='4':
       arg=input('请输入需要查询的信息:')
       search(arg)

    if number=='5':

        exit()

 

posted on 2018-07-23 22:59  lvshui  阅读(104)  评论(0编辑  收藏  举报