python基础10--time和random等常用模块与包

查询功能:

##运行的功能
def fench(data):
    print("\033[1;43m这是查询功能\033[0m")     ##注意颜色的操作里面的符号是;
    print("\033[1;43m用户数据是:\033[0m",data)
    backend_data='backend %s' %data
    with open('查询文件',"r") as read_f:
        tag=False    ##加入变量表示状态
        ret=[]
        for read_line in read_f:
            if read_line.strip() == backend_data:

                tag=True
                continue
            if read_line.startswith("backend") and tag:
                break
            if tag:
                print("\033[1;45m%s\033[0m" %read_line,end="")
                ret.append(read_line)
    return ret

...其他功能模块

if __name__== "__main__":  ##为了规范,下面调试代码


    msg=   '''
          1:查询
          2:添加
          3:修改
          4:删除
          5:退出
          '''

    msg_dic={
        '1':fench,
        '2':add,
        '3':change,
        '4':delete
            }

    while True:
        print(msg)
        choice=input("请输入你的选项:").strip()
        if  not choice: continue
        if choice == '5':break
        data=input("请输入你的数据:").strip()
        res=msg_dic[choice](data)
        print(res)
View Code

 

修改功能:

__author__ = 'YT'
import os
##运行的功能
def fench(data):
    print("\033[1;43m这是查询功能\033[0m")     ##注意颜色的操作里面的符号是;
    print("\033[1;43m用户数据是:\033[0m",data)
    backend_data='backend %s' %data
    with open('查询文件',"r") as read_f:
        tag=False    ##加入变量表示状态
        ret=[]
        for read_line in read_f:
            if read_line.strip() == backend_data:

                tag=True
                continue
            if read_line.startswith("backend") and tag:
                break
            if tag:
                print("\033[1;45m%s\033[0m" %read_line,end="")
                ret.append(read_line)
    return ret


def add(data):
    pass

def change(data):
    print("用户传入的数据",data)
    backend=data[0]['backend']
    backend_data='backend %s' %backend
    old_sever_record='%ssever %s weight %s maxconn %s\n' %(' '*4, data[0]['record']['sever'],data[0]['record']['weight'],data[0]['record']['maxconn'])
    new_sever_record='%ssever %s weight %s maxconn %s\n' %(' '*4, data[1]['record']['sever'],data[1]['record']['weight'],data[1]['record']['maxconn'])
    res=fench(backend)
    print('旧的记录',old_sever_record)
    if not res or old_sever_record not in res:
        return '修改记录不存在'
    else:
        index=res.index(old_sever_record)
        res[index]=new_sever_record
    res.insert(0,'backend %s\n' %backend_data)
    with open('查询文件','r') as read_f ,\
             open('文件','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('查询文件','a.txt')
    os.rename('文件','查询文件')
    os.remove('a.txt')














def delete():
    pass



if __name__== "__main__":  ##为了规范,下面调试代码


    msg=   '''
          1:查询
          2:添加
          3:修改
          4:删除
          5:退出
          '''

    msg_dic={
        '1':fench,
        '2':add,
        '3':change,
        '4':delete
            }

    while True:
        print(msg)
        choice=input("请输入你的选项:").strip()
        if  not choice: continue
        if choice == '5':break
        data=input("请输入你的数据:").strip()

        if choice != '1':
            data=eval(data)
        res=msg_dic[choice](data)
        print(res)
View Code

 

由于查询和修改功能都有相同的文件处理部分,将相同的部分放在同一个函数,代码更加具有可读性(程序的解耦)

def file_handle(backend_data,res=None,type='fench'):
 if type == 'fench':
     with open('查询文件',"r") as read_f:
        tag=False    ##加入变量表示状态
        ret=[]
        for read_line in read_f:
            if read_line.strip() == backend_data:

                tag=True
                continue
            if read_line.startswith("backend") and tag:
                break
            if tag:
                print("\033[1;45m%s\033[0m" %read_line,end="")
                ret.append(read_line)
     return ret
 elif type == 'change':
        with open('查询文件','r') as read_f ,\
             open('文件','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('查询文件','a.txt')
                    os.rename('文件','查询文件')
                    os.remove('a.txt')
View Code

 

 

模块:一个.py文件称为一个模块

分为:1.python标准库        2.第三方模块        3.应用程序自定义模块

包:是一个带有__init__.py文件的文件夹,用于组织模块

 

import:1.执行调用的模块文件    2.引入变量名

调用模块的两种方式:

import cal
print(cal.add(7,5))
print(cal.sub(7,5))


#from cal import *  不推荐用
from cal import sub
from cal import add
print(sub(7,5))
print(add(7,5))
View Code

ps:注意import只能在执行文件那一层目录进行寻找

 

寻找多层包下面的py文件的方式

from 基础.module import cal      #from后面跟py文件的路径,用.隔开
from 基础.module.cal import add


from 基础 import module #执行module里面的_init_文件,唯一不支持的调用方式
print(cal.add(2,3))
View Code

__name__的使用:

1.在执行文件中,__name__=__main__

2.在被调用文件中,__name__=__main__

作用:1.用于被调用文件的测试     2.防止执行文件变成被调用文件,让别人执行你的主程序

 

 

 

Python标准库的模块:

time模块:

import time
#时间戳(从1970年开始以秒计算,常用于时间的计算)
print(time.time())
#结果为:1589333027.17818

#结构化时间---当地时间
print(time.localtime())
#结果为:time.struct_time(tm_year=2020, tm_mon=5, tm_mday=13, tm_hour=9, tm_min=25, tm_sec=3, tm_wday=2, tm_yday=134, tm_isdst=0)

#结构化时间--世界标准时间(与我国相差8小时)
print(time.gmtime())
#结果为:time.struct_time(tm_year=2020, tm_mon=5, tm_mday=13, tm_hour=1, tm_min=26, tm_sec=38, tm_wday=2, tm_yday=134, tm_isdst=0)

#时间戳转化为结构化时间
print(time.localtime(time.time()))  #gmtime同理

#结构化时间转化为时间戳
print(time.mktime(time.localtime()))

#结构化时间转化成字符串时间
print(time.strftime("%Y-%m-%d %X",time.localtime()))   #结果为:2020-05-13 09:32:50

#字符串时间转化成结构化时间
print(time.strptime("2016:12:23:17:12:12","%Y:%m:%d:%X"))
#结果为:time.struct_time(tm_year=2016, tm_mon=12, tm_mday=23, tm_hour=17, tm_min=12, tm_sec=12, tm_wday=4, tm_yday=358, tm_isdst=-1)

#将结构化时间转化成固定的字符串时间
print(time.asctime())
#将时间戳时间转化成固定的字符串时间
print(time.ctime())
#两个结果都为:Wed May 13 09:37:57 2020



import datetime
print(datetime.datetime.now())
#结果为:Wed May 13 09:37:57 2020
View Code

 

 

random模块:

import random
print(random.random())   #随机取0到1之间的浮点数
print(random.randint(1,4))   #随机取【1,4】之间的整数
print(random.randrange(1,4))  #随机取【1,4)之间的整数
print(random.choice([11,22,33,44]))  #随机取列表中的一个数
print(random.sample([11,22,33,34,56,76],2)) #随机取列表中2个数,取几个数由自己决定
print(random.uniform(1,4))  #随机取1到4之间的浮点数

ret=[1,2,4,5,7,8,9]
s=random.shuffle(ret)
print(ret)              #随机打乱列表的顺序
View Code

 

验证码例子

import random
def v_code():
    ret=""
    for i in range(6):
        num=random.randint(0,9)
        alf=chr(random.randint(65,122))
        s=str(random.choice([num,alf]))  ##注意要把数字和字母转换为字符串
        ret += s
    return ret
print(v_code())
View Code

 

posted @ 2020-04-29 16:41  sakura*gyt  阅读(143)  评论(0)    收藏  举报