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}}]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章