day21函数的文件处理和模块

==============模块==================
1.模块的调用
    import 执行的两件事
    1.引入变量名称
    2.执行导入文件
    #import
    from cal import *#不推荐,不知道后面的人使用是那个
    from cal import add
    from cal import sub
    #包是用来组织模块的文件
    导入包就用的是from ** import *
    层与层之间用..
    if __name__='__main__'
    执行2个作用:
    第一个是被调用不会全部执行,第二个是
    1.如果在被调用的文件里面,在被调用的时候不会执行,
    2.不会被调用
    模块介绍
    1.os  sys  time  json eval xml .conf logger re 模块*正则表达式
    ============import功能介绍============================
    #import 会把全部的执行一遍
    import os
    import sys
    import cal#执行2件事情,第一先全部执行一遍,第二把传递过去的再执行一次
    a=(cal.add(1,4))
    b=(cal.sub(3,7))
    print(a)
    print(b)
    #import执行两件事情
    #1.执行调用的文件
    #2.
    print(sys.path)#sys.path 就是执行文件的路径
    ================import调用功能的使用=================
    import time
    # x='hello'
    # a=time.process_time()
    # print(a)
    from web.web1.web3.cal import add
    #print(add(1,7))

    from web.web1 import web3#执行web3__init__文件,唯一一种不支持的调用方式
    print(__name__)
    ========tag练习====================
    import os
    tag=True
    while tag:
        print('lever')
        choice=input("lever>>").strip()
        if choice == 'quit': break
        if choice == 'quit_all': tag == False
        while tag:
            print("lever2")
            choice=input('lever2>>').strip()
            if choice == 'quit': break
            if choice == 'quit_all': tag == False
            while tag:
                print('lever3')
                choice=input("lever3>>").strip()
                if choice == 'quit':break
                if choice == 'quit_all':tag==False
    os.rename('a.txt','a.txt.bak')
    ======================随机函数============
    import random
    ret=random.random()
    print(ret)
    res=random.randint(1,3)
    print(res)
    rea=random.randrange(1,3)
    print(rea)
    print(random.choice([1,'23',[3,4],['sf','af']]))#一个
    print(random.sample([11,22,33,44,55],2))#两个

    red=[1,3,4,46,61]
    random.shuffle(red)
    print(red)
    def v_code():
        ret=""
        for i in range(5):
            num=random.randint(0,9)
            alf=chr(random.randint(65,122))
            s=str(random.choice([num,alf]))
            ret+=s
        return ret
    print(v_code())
    =================time函数=================
    import time
    #时间戳
    print(time.time())#是一个秒 是1970年1月1日  unix时间
    print(time.localtime())#当地时间
    t=time.localtime()
    print(t.tm_year)
    print(t.tm_wday)
    print(t.tm_yday)
    print(time.gmtime())#结构化时间UTC
    #字符串时间
    #将结构化时间转化为时间戳
    print(time.mktime(time.localtime()))
    ------------将结构化时间转化成字符串时间
    print(time.strftime("%Y-%m-%d %X",time.localtime()))
    #------将字符串时间转化为结构化时间
    print(time.strptime("2018:06:03:18:20:36","%Y:%m:%d:%X"))
    #固定式时间格式看时间
    print(time.asctime())
    print(time.ctime())
    import datetime
    print(datetime.datetime.now())


    =========================re正则表达式=================
    import re
    print(re.findall(r"123","123"))

=======================文件处理完整版本============
    #strip()去除左右两边的空额
    #eval()提取数据类型,
    #1.函数
    #2.文件处理
    #3.tag的用法
    #4.程序的解耦
    import os
    #def fild_handle(backend_data,res=None,type='fetch'):
    def file_handle(filename,backend_data,record_list=None,type='fetch'): #type fetch append change
        new_file=filename+'_new'
        bak_file=filename+'_bak'

        if type=='fetch':
            r_list=[]
            #with open('haproxy.conf','r') as read_f:
            with open(filename,'r') as f:
                tag = False
                for line in f:
                    if line.strip()==backend_data:
                        tag=True
                        continue
                    if tag and line.startswith('backend'):
                        break
                    if tag and line:
                        r_list.append(line.strip())
                    for line in r_list:
                        print(line)
                    return r_list
        elif type =='append':
            with open(filename,'r') as read_file,\
                open(new_file,'w') as write_file:
                for r_line in read_file:
                    write_file.write(r_line)

                for new_file in record_list:
                    if new_file.startwith('backend'):
                        write_file.write(new_file+'\n')
                    else:
                        write_file.write('%s%s\n'%(''*8,new_file))
            os.rename(filename,bak_file)
            os.rename(new_file,filename)
            os.remove(bak_file)
        elif type=='change':
            with open(filename,'r') as read_file,\
                open(new_file,'w') as write_file:
                tag=False
                has_write=False
                for r_line in read_file:
                    if r_line.strip() == backend_data:
                        tag=True
                        continue
                    if tag and r_line.startswith('backend'):
                        tag=False
                    if not tag:
                        write_file.write(r_line)
                    else:
                        if not has_write:
                            for new_file in record_list:
                                if new_file.startwith('backend'):
                                    write_file.write(new_file+'\n')
                                else:
                                    write_file.write('%s%s\n'%(''*8,new_file))
                            has_write=True
            os.rename(filename,bak_file)
            os.rename(new_file,filename)
            os.remove(bak_file)
        #         #ret=[]
        #         for read_line in read_f:
        #             if read_line.strip() == backend_data:
        #                 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
        # if 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_data:
        #                     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:
        #                         for record in res:
        #                             write_f.write(record)
        #                         has_write = True
        #         os.rename('haproxy.conf', 'haproxy.conf.bak')
        #         os.rename('haproxy.cong_new', 'haproxy.conf')
        #         os.remove('haproxy.bak')

    def fetch(data):
        # print('\033[1;43m这是查询功能\033[0m')
        # print('\033[1;43m用户数据是\033[0m',data)
        # backend_data='backend %s'%data
        # return fild_handle(backend_data)
        backend_data='backend %s'%data
        return file_handle('haproxy.conf',backend_data,type='fetch')
    def add(data):
        backend=data['backend']
        record_list=fetch(backend)
        current_record='server %s %s weight %s maxconn %s'%(data['record']['server'], \
                                                            data['record']['server'], \
                                                            data['record']['weight'], \
                                                            data['record']['maxconn'])
        backend_data='backend %s'%backend
        if not record_list:
            record_list.append(backend_data)
            record_list.append(current_record)
            file_handle('harpoxy.conf',backend_data,record_list,type='append')
        else:
            record_list.insert(0,backend_data)
            if current_record not in record_list:
                record_list.append(current_record)
            file_handle('harpoxy.conf',backend_data,record_list,type='change')
    def remove(data):
        backend=data['backend']
        record_list=fetch(backend)
        current_record='server %s %s weight %s maxconn %s' %(data['record']['server'],\
                                                        data['record']['server'],\
                                                        data['record']['weight'],\
                                                        data['reocrd']['maxconn'])
        backend_data='backend %s'%backend
        if not record_list or current_record not in record_list:
            return print('\033[33;1m无记录\033[0m')
        else:
            #处理record_list
            record_list.insert(0,backend_data)
            record_list.remove(current_record)
            file_handle('haproxy,conf',backend_data,record_list,type='change')

    def change(data):
        print('这是修改功能')
        print("用户输入的数据时%", data)
        backend = data[0]['backend']  # 找到文件的中信息
        backend_data = 'backend %s' % backend  # backend www.oldboy1.org
        old_server_record = '%ssserver %s %s weight %s maxconn %s\n' % ('' * 8, data[0]['record']['server'],
                                                                        data[0]['record']['server'],
                                                                        data[0]['record']['weight'],
                                                                        data[0]['record']['maxconn'])
        new_server_record = '%ssserver %s %s weight %s maxconn %s\n' % ('' * 8, data[1]['record']['server'],
                                                                        data[1]['record']['server'],
                                                                        data[1]['record']['weight'],
                                                                        data[1]['record']['maxconn'])
        print('用户想要修改的记录是', old_server_record)
        res = fetch(backend)
        print('来自change函数--》》', res)
        if not res or old_server_record not in res:
            return '你要修改的记录不存在'

        else:
            index = res.index(old_server_record)
            res[index] = new_server_record
        res.insert(0, '%s\n' % backend_data)
        file_handle(backend_data,res=res,type='change')
    def qita():
        pass
    def delete():
        pass
    if __name__=='__main__':
        print("test")
        msg='''
        1.查询
        2.添加
        3.修改
        4.删除
        5.退出 
        '''
        menu_dic={
            '1':fetch,
            '2':add,
            '3':remove,
            '4':change,
            '5':exit,
            '6':qita,
        }
        while True:
            print(msg)
            choice=input('输入你想要的选项:').strip()
            if not choice:continue
            if choice=='5':break
            #date='www.oldboy1.org'
            data=input('输入你的数据:').strip()
            #menn_dic[choice](data)==fetch(data)
            if choice != '1':
                data=eval(data)
            menu_dic[choice](data)
            #res=msg_dic[choice](data)
            #print('最终的结果是',res)
        #[{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]

猜你喜欢

转载自blog.csdn.net/qq_37311616/article/details/80561057
今日推荐