码迷,mamicode.com
首页 > 其他好文 > 详细

sed 作业;掌握 函数式编程,文件处理,tag用法,程序解耦

时间:2018-02-28 01:03:52      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:for   write   ret   serve   使用   退出   hid   return   div   

sed作业 : 对文件实现查找,修改的功能

技术分享图片
import os            ### 为了修改后面的文件名

def fetch(date):
    # print(‘\033[1;44m这是查询功能\033[0m‘)
    # print(‘\033[1;44m用户输入的数据是%s\033[0m‘%date)
    backend_date = ‘backend %s‘%date
    with open(‘haproxy.conf‘,‘r‘) as read_f:
        tag = False
        ret = []
        for read_line in read_f:
            if read_line.strip() == backend_date:
                tag = True
                continue
            if tag and read_line.startswith(‘backend‘):
                break
            if tag:
                print(‘\033[1;45m%s\033[0m‘%read_line,end=‘‘)
                ret.append(read_line)
    return ret

def add():
    pass

def change(date):
    ### 用户输入的date是[{‘backend‘:‘www.oldboy1.org‘,‘record‘:{‘server‘:‘2.2.2.5‘,‘weight‘:30,‘maxconn‘:4000}},{‘backend‘:‘www.oldboy1.org‘,‘record‘:{‘server‘:‘2.2.2.8‘,‘weight‘:30,‘maxconn‘:4000}}]
    # print(‘这是修改功能‘)
    # print(‘用户输入的数据是%s‘%date)
    backend = date[0][‘backend‘]     ### 文件中的一条记录 www.oldboy1.org
    backend_date = ‘backend %s‘ %backend
    ## ,‘record‘: ‘server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000‘
    old_server_record = ‘%sserver %s %s weight %s maxconn %s\n‘ %(‘ ‘*8,date[0][‘record‘][‘server‘],
                                                                   date[0][‘record‘][‘server‘],
                                                                   date[0][‘record‘][‘weight‘],
                                                                   date[0][‘record‘][‘maxconn‘])
    print(‘用户想要修改的记录是:‘,old_server_record)
    new_server_record =  ‘%sserver %s %s weight %s maxconn %s\n‘ % (‘ ‘ * 8, date[1][‘record‘][‘server‘],
                                                                 date[1][‘record‘][‘server‘],
                                                                 date[1][‘record‘][‘weight‘],
                                                                 date[1][‘record‘][‘maxconn‘])
    print(‘用户要修改成的结果是:‘,new_server_record)
    res = fetch(backend)
    print(‘来自change函数--->‘,res)
    # if not res:
    #     print(‘你要修改的记录不存在‘)
    # if old_backend_record in res:
    #     print(‘你要修改的记录不存在‘)    ### 二个return 一样 可合并
    if not res or old_server_record not in res:
        return ‘你要修改的记录不存在‘
    else:
        index = res.index(old_server_record)   ### 根据值取索引
        res[index] = new_server_record    ###  把要改的那条  根据索引更改值
        # print(‘列表中的值已经修改‘)
    res.insert(0,‘%s\n‘%backend_date)  ### 把开头头加进去
    with open(‘haproxy.conf‘,‘r‘) as read_f,            open(‘haproxy.conf_new‘,‘w‘) as write_f:
        tag = False
        has_write = False
        for read_line in read_f:
            if read_line.strip() == backend_date:
                tag = True
                continue
            if tag and read_line.startswith(‘backend‘):
                tag = False
            if not tag:
                write_f.write(read_line)
            else:
                if not has_write:     ###  为防止遇到一个sever,就写一次 ,在写一个状态
                    for record in res:
                        write_f.write(record)
                    has_write = True
    os.rename(‘haproxy.conf‘,‘haproxy.conf.bak‘)
    os.rename(‘haproxy.conf_new‘,‘haproxy.conf‘)
    os.remove(‘haproxy.conf.bak‘)

def delate():
    pass

if __name__ == ‘__main__‘:
    msg = ‘‘‘
    1:查询
    2:修改
    3:添加
    4:删除
    5:退出
    ‘‘‘
    msg_dic = {
        ‘1‘:fetch,
        ‘2‘:change,
        ‘3‘:add,
        ‘4‘:delate
    }
    while True:
        print(msg)
        choice = input(‘请输入你的选项:‘).strip()
        if not choice:
            continue
        if choice == ‘5‘:
            break
        date = input(‘请输入你的数据:‘).strip()
        if choice != ‘1‘:
            date = eval(date)
        res = msg_dic[choice](date)
        print(res)
不使用程序解耦
技术分享图片
import os            ### 为了修改后面的文件名
def fild_handler(backend_date,res = None,type = ‘fetch‘):
    if type == ‘fetch‘:
        with open(‘haproxy.conf‘, ‘r‘) as read_f:
            tag = False
            ret = []
            for read_line in read_f:
                if read_line.strip() == backend_date:
                    tag = True
                    continue
                if tag and read_line.startswith(‘backend‘):
                    break
                if tag:
                    print(‘\033[1;45m%s\033[0m‘ % read_line, end=‘‘)
                    ret.append(read_line)
        return ret
    elif type == ‘change‘:
        with open(‘haproxy.conf‘, ‘r‘) as read_f,                 open(‘haproxy.conf_new‘, ‘w‘) as write_f:
            tag = False
            has_write = False
            for read_line in read_f:
                if read_line.strip() == backend_date:
                    tag = True
                    continue
                if tag and read_line.startswith(‘backend‘):
                    tag = False
                if not tag:
                    write_f.write(read_line)
                else:
                    if not has_write:  ###  为防止遇到一个sever,就写一次 ,在写一个状态
                        for record in res:
                            write_f.write(record)
                        has_write = True
        os.rename(‘haproxy.conf‘, ‘haproxy.conf.bak‘)
        os.rename(‘haproxy.conf_new‘, ‘haproxy.conf‘)
        os.remove(‘haproxy.conf.bak‘)


def fetch(date):
    # print(‘\033[1;44m这是查询功能\033[0m‘)
    # print(‘\033[1;44m用户输入的数据是%s\033[0m‘%date)
    backend_date = ‘backend %s‘%date
    return fild_handler(backend_date)


def add():
    pass

def change(date):
    ### 用户输入的date是[{‘backend‘:‘www.oldboy1.org‘,‘record‘:{‘server‘:‘2.2.2.5‘,‘weight‘:30,‘maxconn‘:4000}},{‘backend‘:‘www.oldboy1.org‘,‘record‘:{‘server‘:‘2.2.2.8‘,‘weight‘:30,‘maxconn‘:4000}}]
    # print(‘这是修改功能‘)
    # print(‘用户输入的数据是%s‘%date)
    backend = date[0][‘backend‘]     ### 文件中的一条记录 www.oldboy1.org
    backend_date = ‘backend %s‘ %backend
    ## ,‘record‘: ‘server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000‘
    old_server_record = ‘%sserver %s %s weight %s maxconn %s\n‘ %(‘ ‘*8,date[0][‘record‘][‘server‘],
                                                                   date[0][‘record‘][‘server‘],
                                                                   date[0][‘record‘][‘weight‘],
                                                                   date[0][‘record‘][‘maxconn‘])
    print(‘用户想要修改的记录是:‘,old_server_record)
    new_server_record =  ‘%sserver %s %s weight %s maxconn %s\n‘ % (‘ ‘ * 8, date[1][‘record‘][‘server‘],
                                                                 date[1][‘record‘][‘server‘],
                                                                 date[1][‘record‘][‘weight‘],
                                                                 date[1][‘record‘][‘maxconn‘])
    print(‘用户要修改成的结果是:‘,new_server_record)
    res = fetch(backend)
    print(‘来自change函数--->‘,res)
    # if not res:
    #     print(‘你要修改的记录不存在‘)
    # if old_backend_record in res:
    #     print(‘你要修改的记录不存在‘)    ### 二个return 一样 可合并
    if not res or old_server_record not in res:
        return ‘你要修改的记录不存在‘
    else:
        index = res.index(old_server_record)   ### 根据值取索引
        res[index] = new_server_record    ###  把要改的那条  根据索引更改值
        # print(‘列表中的值已经修改‘)
    res.insert(0,‘%s\n‘%backend_date)  ### 把开头头加进去
    fild_handler(backend_date,res = res,type = ‘change‘)


def delate():
    pass

if __name__ == ‘__main__‘:
    msg = ‘‘‘
    1:查询
    2:修改
    3:添加
    4:删除
    ‘‘‘
    msg_dic = {
        ‘1‘:fetch,
        ‘2‘:change,
        ‘3‘:add,
        ‘4‘:delate
    }
    while True:
        print(msg)
        choice = input(‘请输入你的选项:‘).strip()
        if not choice:
            continue
        if choice == ‘5‘:
            break
        date = input(‘请输入你的数据:‘).strip()
        if choice != ‘1‘:
            date = eval(date)
        res = msg_dic[choice](date)
        print(res)
使用程序解耦

掌握 函数式编程,文件处理,tag用法,程序解耦 

 

sed 作业;掌握 函数式编程,文件处理,tag用法,程序解耦

标签:for   write   ret   serve   使用   退出   hid   return   div   

原文地址:https://www.cnblogs.com/glh-ty/p/8481547.html

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