1. 基础语法
1.1 time模块
(1)time.time()函数
import timetime = time.time()#返回一个浮点数,称为UNIX纪元时间戳,即1970.1.1 00:00 开始的秒数
(2)time.sleep()函数
time.sleep(5)#希望程序暂停的时间
(3)round()四舍六入五成双
now = time.time()round(now,2)#round函数取到小数点后几位,5前为奇数,舍5入1;5前为偶数,舍5不进
1.2 datetime模块
import datetimedt = datetime.datetime.now()#返回一个datetime对象(年,月,日,时,分,秒),dt.year,dt.month等得到特定时刻的datetime对象
(1)datetime 与 time转换
datetime.datetime.fromtimestamp(10000)>>>datetime.datetime(1970,1,12,5,46,40)datetime.datetime.fromtimestamp(time.time())>>>datetime.datetime(,2,27,11,13,0,604980)#函数 fromtimestamp相互转换
(2)timedelta数据类型
delta = datetime.timedelta(days,hours,minutes,seconds)#返回以(天,秒,微秒)来表示delta.total_seconds()#返回以秒计算的时间#timedelta表示一段时间,并且可以计算
(3)将datetime对象转换为字符串
datetime.strftime()函数将datetime对象转换为格式化的字符串
datetime.strptime()函数将格式化的字符串转换为datetime对象
dt = datetime.datetime(,11,12,11,12,0)dt.strftime('%Y/%m/%d %H:%M:%S) #datetime 到字符串datetime.datetime.strptime('/10/21 16:29:00' , '%Y/%m/%d %H:%M:%S') #格式化字符串到datetime对象
1.3 多线程
(1)多线程启动
import threading#创建一个Thread对象threadobj = threading.Thread(target = fx)#fx为想要以第二线程启动的函数名称#第二个线程开始threadobj.start()
(2)多参数
#常规参数作为一个列表传给args,关键字参数作为一个字典传给kwargsthreadobj = threading.Thread(target = print , args =['cats','dog','rabbit'] , kwargs = {'sep}':'&')threadobj.start()>>>'cats&dog&rabbit
注意:多线程可能会由于同时读写变量,导致相互干扰产生并发问题,当创建一个新的Thread对象时,要确保目标函数只使用该函数中的局部变量,从而避免并发问题。
1.4 从python启动其他程序
import subprocesscalobj= subprocess.Popen('C:\\Windows\\System32\\calc.exe')#exe的存放地址,返回一个Popen 对象
Popen对象有两个方法:POLL方法和WAIT方法
calobj.poll():若此进程在调用poll方法时仍在执行,则返回None,若进程终止:返回0为无错终止,返回1则为错误导致终止
calobj.wait():将阻塞,直到启动的进程终止(希望你的程序暂停,知道用户完成其他程序)
Popen的命令行参数:想Popen穿第一个列表,第一个字符是可执行程序名,后续字符串是该程序启东市,传递给该程序的命令行参数。
subprocess.Popen(['C:\\Windows\\notepad.exe'.'C:\\'hello.txt'])
2.实例应用
2.1 多线程下载XKCD线程
/3/21 19:09import threading,requests,bs4,osos.makedirs('XKCD',exist_ok = True)#定义下载函数def downloadxkcd(startcomic , endcomic):for urlnum in range(startcomic,endcomic):print('Downloading comics %d'%urlnum)res = requests.get('/'+str(urlnum)+'/')res.raise_for_status()soup = bs4.BeautifulSoup(res.text)comicelem = soup.select('#comic img')if comicelem == None:print("Could't find the image")else:comicurl = comicelem[0].get('src')#下载图片print('Downloading image from %s'%comicurl)res = requests.get('https:'+comicurl)res.raise_for_status()#保存到当地imagefile = open(os.path.join('xkcd',os.path.basename(comicurl)),'wb')for chunk in res.iter_content(100000):imagefile.write(chunk)imagefile.close()#创建并启动线程downloadthreads = []for i in range(0,1400,100):downloadthread = threading.Thread(target= downloadxkcd , args= (i,i+99))downloadthreads.append(downloadthread)downloadthread.start()#等待所有进程结束for download in downloadthreads:download.join()print('Done')
2.2 简单倒计时
# /3/21 19:04import time,subprocesstotaltime = 10while totaltime > 0 :print(totaltime)time.sleep(1)totaltime -= 1subprocess.Popen(['start','alarm.wav'],shell= True)
3.课后习题
3.1 美化的秒表
# /3/21 19:40import time#显示用户指令print("Press Enter to begin ,then press Enter to stop ,press ctrl+c to quit")input()print('Started')starttime = time.time()lasttime = starttimelapnum = 1#记录并打印单圈时间try:while True:input()laptime = round(time.time()-lasttime,2)totaltime = round(time.time() - starttime , 2)print('Lap # %s: %s (%s)' %(lapnum,str(totaltime).rjust(8),str(laptime).rjust(8)),end='')lapnum += 1lasttime = time.time()except KeyboardInterrupt:print('\nDone')#注:在pycharm中运行,输入ctrl-c 程序停不下来,不过在CMD中运行可以停下
3.2 计划的web漫画下载(检查漫画更新模块不会)
在按规定的时刻检查是否有漫画更新,有的话进行下载。这里用到了schedule模块,以运行计算器为例:
import schedule,subprocessdef job():subprocess.Popen('C:\\Windows\\System32\\calc.exe')schedule.every().day.at("20:41").do(job) #在每一天的规定时刻运行jobwhile True:schedule.run_pending() #运行所有可以运行的任务