Python让繁琐工作自动化——chapter15 保持时间、计划任务和启动程序

xiaoxiao2021-02-28  50

1. 基础语法

1.1 time模块

(1)time.time()函数
import time time = 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 datetime dt = 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(2015,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对象

strftime指令 strftime指令含义%Y带世纪的年份,如‘2014’%y不带世纪的年份,‘00’-‘99’%m数字表示的月份,‘01’-‘12’%B完整的月份,‘July’%b简写的月份,‘Jul’%d一月中的第几天,‘01’-‘31’%j一年中的第几天,‘001’-‘366’%w一周中的第几天,‘0’(周日)-‘6’(周六)%A完整的周几,‘Monday’%a简写的周几,‘Mon’%H小时(24h),'00'-'23'%h小时(12h),‘01’-‘12’%M分%S秒%p‘AM/'PM’%%% dt = datetime.datetime(2017,11,12,11,12,0) dt.strftime('%Y/%m/%d %H:%M:%S) #datetime 到字符串 datetime.datetime.strptime('2015/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,关键字参数作为一个字典传给kwargs threadobj = threading.Thread(target = print , args =['cats','dog','rabbit'] , kwargs = {'sep}':'&') threadobj.start() >>>'cats&dog&rabbit注意:多线程可能会由于同时读写变量,导致相互干扰产生并发问题,当创建一个新的Thread对象时,要确保目标函数只使用该函数中的局部变量,从而避免并发问题。

1.4 从python启动其他程序

import subprocess calobj= 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线程

2018/3/21 19:09 import threading,requests,bs4,os os.makedirs('XKCD',exist_ok = True) #定义下载函数 def downloadxkcd(startcomic , endcomic): for urlnum in range(startcomic,endcomic): print('Downloading comics %d'%urlnum) res = requests.get('https://xkcd.com/'+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 简单倒计时

# 2018/3/21 19:04 import time,subprocess totaltime = 10 while totaltime > 0 : print(totaltime) time.sleep(1) totaltime -= 1 subprocess.Popen(['start','alarm.wav'],shell= True)

3.课后习题

3.1 美化的秒表

# 2018/3/21 19:40 import time #显示用户指令 print("Press Enter to begin ,then press Enter to stop ,press ctrl+c to quit") input() print('Started') starttime = time.time() lasttime = starttime lapnum = 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 += 1 lasttime = time.time() except KeyboardInterrupt: print('\nDone') #注:在pycharm中运行,输入ctrl-c 程序停不下来,不过在CMD中运行可以停下

3.2 计划的web漫画下载(检查漫画更新模块不会)

在按规定的时刻检查是否有漫画更新,有的话进行下载。这里用到了schedule模块,以运行计算器为例:

import schedule,subprocess def job(): subprocess.Popen('C:\\Windows\\System32\\calc.exe') schedule.every().day.at("20:41").do(job) #在每一天的规定时刻运行job while True: schedule.run_pending() #运行所有可以运行的任务
转载请注明原文地址: https://www.6miu.com/read-2625835.html

最新回复(0)