Python开发常用模块

来源:互联网 发布:淘宝新店有流量扶持吗 编辑:程序博客网 时间:2024/04/30 14:59

1 时间模块与定时调用

1.1 等间隔定时调用,步长小于或等于1小时

import time

##### 版本1

def test():

    print("程序执行成功,执行时间为:",time.ctime(time.time()))

 

##c=5     #5秒钟对应的描述

c=5*60  #5分钟对应的描述

##c=60*60  #1小时对应的描述

 

#算法起始运行时间

start=((time.time()+c)//c)*c  #下一个运行的时刻整点

print('本次执行时间:', time.ctime(time.time()))  #调用的时间点到了!

print('修正调用时间:', time.ctime(start))

time.sleep(start-time.time())  #睡眠时间

 

while 1:

    print('本次执行时间:', time.ctime(time.time()))  #调用的时间点到了!

    print('修正调用时间:', time.ctime(round(time.time()/c)*c))

    print(round(time.time()/c)*c)

    test()

##    print('当前系统时间:', time.ctime(time.time()))

    start=((time.time()+c+1)//c)*c #下次运行时间,加上0.01的修正

    print('下次执行时间:', time.ctime(start))

    #睡眠时间

##    print('睡眠:',start-time.time())

time.sleep(start-time.time())  #睡眠时间

1.2 非等间隔定时调用,步长大于1小时

##  大于1小时,间隔的定时调用

import datetime

import time

import logging

 

def myfunc1():

    print('执行函数1')

def myfunc2():

    print('执行函数2')

def myfunc3():

    print('执行函数3')

def myfunc4():

    print('执行函数4')

 

## 当前时间

now=datetime.datetime.now()

 

## 下一天

last=now+datetime.timedelta(days=1) #days,microseconds, seconds

last=last.replace(hour=0, minute=0, second=0,microsecond=0)

 

 

#调用起始时间

print('当前调用时间:', now.ctime())  #注释行

print('下次调用时间:', last.ctime()) #注释行

 

## 等待的时间

sleep=last.timestamp()-now.timestamp()

time.sleep(sleep) ##第一次等待的时间

 

 

while 1:

    ##00:00调用预处理模块

    print('函数执行!执行时间为:',datetime.datetime.now())

   p_start_time=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime('%Y-%m-%d12:00')

    p_end_time =datetime.datetime.now().strftime('%Y-%m-%d 00:00')

    p_rate = 0.05

    myfunc1()  ##函数1

 

    ##02:00调用预处理模块

   now=datetime.datetime.now()                                #第一次调用完结束时间

    last=now.replace(hour=2,minute=0, second=0, microsecond=0) #02:00第二次调用时间

    print('当前调用时间:', now.ctime())  #注释行

    print('下次调用时间:', last.ctime()) #注释行

   sleep=last.timestamp()-now.timestamp()

   time.sleep(sleep)                                          #第二次调用前的休眠时间

    print('函数执行!执行时间为:',datetime.datetime.now())

   p_start_time=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime('%Y-%m-%d00:00')

    p_end_time =datetime.datetime.now().strftime('%Y-%m-%d 00:00')

    myfunc2()  ##函数2

   

   

    if now.weekday()==0:

        ##周一03:00调用

       now=datetime.datetime.now()

       last=now.replace(hour=3, minute=0, second=0, microsecond=0) #12:00第二次调用时间

        print('当前调用时间:', now.ctime())  #注释行

        print('下次调用时间:', last.ctime()) #注释行

       sleep=last.timestamp()-now.timestamp()

       time.sleep(sleep)

        print('函数执行!执行时间为:',datetime.datetime.now())

       p_start_time=(datetime.datetime.now()-datetime.timedelta(days=90)).strftime('%Y-%m-%d00:00')

       p_end_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00')

       myfunc3()  ##函数3

 

        ##周一06:00调用

       now=datetime.datetime.now()

       last=now.replace(hour=6, minute=0, second=0, microsecond=0) #12:00第二次调用时间

        print('当前调用时间:', now.ctime())  #注释行

        print('下次调用时间:', last.ctime()) #注释行

       sleep=last.timestamp()-now.timestamp()   

       time.sleep(sleep)

        print('函数执行!执行时间为:',datetime.datetime.now())

       p_start_time=(datetime.datetime.now()-datetime.timedelta(days=90)).strftime('%Y-%m-%d00:00')

       p_end_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00')

       myfunc4()    ##函数4

    else:

        pass

   

    ##12:00调用预处理模块

    now=datetime.datetime.now()

    last=now.replace(hour=12,minute=0, second=0, microsecond=0) #12:00第二次调用时间

    print('当前调用时间:', now.ctime())  #注释行

    print('下次调用时间:', last.ctime()) #注释行

   sleep=last.timestamp()-now.timestamp()

   time.sleep(sleep)                    #第二次调用前的休眠时间

    print('函数执行!执行时间为:',datetime.datetime.now())

   p_start_time=datetime.datetime.now().strftime('%Y-%m-%d 00:00')

    p_end_time =datetime.datetime.now().strftime('%Y-%m-%d 12:00')

    p_rate = 0.05

    myfunc1()  

   

    ## 计算第二天调用时间及休眠时间

    now=datetime.datetime.now()

   last=now+datetime.timedelta(days=1)        #days, microseconds, seconds

    last=last.replace(hour=0,minute=0, second=0, microsecond=0) #下一次执行的时间

    print('当前调用时间:', now.ctime())  #注释行

    print('下次调用时间:', last.ctime()) #注释行

   sleep=last.timestamp()-now.timestamp()

time.sleep(sleep)                             #睡眠时间,至第二日00:00醒来

 

 

2数据的存入与读取

import numpy as np

import pickle

 

A=np.random.randint(10, size=(3, 3))

print('数组A的值为:\n', A) 

 

##以数组的形式存储数据

with open('mydata.pickle', 'wb') as mysavedata:

    pickle.dump(A, mysavedata) 

with open('mydata.pickle', 'rb') as mysavedata:

    B=pickle.load(mysavedata)

print('数组B的值为:\n', B) 

 

3 logging模块与异常处理

import logging

logging.basicConfig(level=logging.DEBUG,  ##制定级别

                   format='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)\

                   s%(message)s',

                   datefmt='%a, %d %b %Y %H:%M:%S',

##                   filename='C:\\Users\\yuanmin\\Desktop\\myapp.log', #指定路径

                   filename='myapp.log',

                   filemode='w')

 

logging.debug("This is debug message")

logging.info("This is info message")

logging.warning("This is warningmessage")

 

def myfunc():  #ZeroDivisionError

    a=1/0

 

try:

    myfunc()

except :

    logging.exception('myfunc()函数执行失败!')

logging.shutdown()

print('调用结束!')

 

 

4多线程测试案例

####   多线程测试案例

#coding=utf-8

import threading

from time import ctime,sleep

 

def music(func):

    for i inrange(10):

       print("运行%s, 时间:%s" %(func,ctime()))

        sleep(1)

def move(func):

    for i inrange(2):

        print("运行%s! 时间%s" %(func,ctime()))

        sleep(5)

##def move1(func):

##    for i inrange(2):

##       print("I was at the %s! %s" %(func,ctime()))

##       sleep(5)

##       

threads = []

t1 = threading.Thread(target=music,args=(u'线程1',))

threads.append(t1)

t2 = threading.Thread(target=move,args=(u'线程2',))

threads.append(t2)

 

if __name__ == '__main__':

    for t inthreads:

       t.setDaemon(True)

       t.start()

    t.join()

  

   print("all over %s" %ctime())

    input("按任意键退出...\n")

##    ifinput("press any key to continue:"):

##        pass

   print("1111111111" )

0 0
原创粉丝点击