下载器和进程池
下載器
import os
from urllib import request
from multiprocessing import Process
#使用面向對象簡單
class Process2(Process):
def init(self,url):
super().init()
self.url=url
def run(self):#Process類中的run函數自動調用
print(‘當前進程’,os.getpid(),end=’’)
print(‘父進程’,os.getppid())
# 文件名將圖片保存
# file_name=url.split(’/’)[-1]
# response=request.urlopen(url)#網絡請求#響應一個對象#urlopen網頁地址網頁地址urlopen
# content=response.read()#獲取相應的內容
# with open(file_name,‘wb’) as fq:#保存
# fq.write(content)
class Process2(Process):
def init(self,url):
super().init()
self.url=url
def run(self):#
if name==‘main’:
urlList=[
‘http://www.langlang2017.com/img/banner’ + str(1) + ‘.png’,
‘http://www.langlang2017.com/img/banner’ + str(2) + ‘.png’
]
for url in urlList:
p=Process2(url)
p.start()
進程池
from multiprocessing import Process
from multiprocessing import Pool
import os,time,random
def worker(msg):
start=time.time()
print(’%s開始執行’%msg)
time.sleep(random.random())
end=time.time()
print(’%s執行結束,用時%0.2f秒’%(msg,end-start))
if name == ‘main’:
p=Pool(3)
for i in range(10):
p.apply_async(func=worker,args=(i,))
p.close()#關閉進程池
p.join()#阻塞使其完成
總結
- 上一篇: python九九乘法表求和,平均数,最大
- 下一篇: 多线程共享全局变量