python基于queue和threading實(shí)現(xiàn)多線程下載實(shí)例
本文實(shí)例講述了python基于queue和threading實(shí)現(xiàn)多線程下載的方法,分享給大家供大家參考。具體方法如下:
主代碼如下:
#download worker queue_download = Queue.Queue(0) DOWNLOAD_WORKERS = 20 for i in range(DOWNLOAD_WORKERS): DownloadWorker(queue_download).start() #start a download worker for md5 in MD5S: queue_download.put(md5) for i in range(DOWNLOAD_WORKERS): queue_download.put(None)
其中downloadworkers.py
類繼承 threading.Thread,重載run方法..在__init__中調(diào)用threading.Thread.__init__(self),
在run方法中實(shí)現(xiàn)耗時(shí)的操作
import threading import Queue import md5query import DOM import os,sys class DownloadWorker(threading.Thread): """""" def __init__(self, queue): """Constructor""" self.__queue = queue threading.Thread.__init__(self) def run(self): while 1: md5 = self.__queue.get() if md5 is None: break #reached end of queue #this is a time-cost produce self._down(md5) print "task:", md5, "finished" def _down(self, md5): config = { 'input':sys.stdin, 'output':'./samples', 'location':'xxx', 'has-fn':False, 'options':{'connect.timeout':60, 'timeout':3600}, 'log':file('logs.txt', 'w'), } print 'download %s...' % (md5) try: data = downloadproc(config['location'], config['options'])#我的下載過(guò)程 if data: dom, fileData = md5query.splited(data) filename = md5 if config['has-fn']: filename = '%s_%s' % (md5, dom.nodeValue2('xxxxxxx', '').encode('utf-8'))#這是我的下載的方法 f = file(os.path.join(config['output'], filename), 'w') f.write(fileData) f.close() print '%s\tok' % (md5) else: print>>config['log'], '%s\t%s' % (md5, 'failed') except Exception, e: print>>config['log'], '%s\t%s' % (md5, str(e))
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
- Python中多線程thread與threading的實(shí)現(xiàn)方法
- Python用threading實(shí)現(xiàn)多線程詳解
- python使用threading獲取線程函數(shù)返回值的實(shí)現(xiàn)方法
- Python 使用threading+Queue實(shí)現(xiàn)線程池示例
- Python線程協(xié)作threading.Condition實(shí)現(xiàn)過(guò)程解析
- Python3 socket即時(shí)通訊腳本實(shí)現(xiàn)代碼實(shí)例(threading多線程)
- python中threading和queue庫(kù)實(shí)現(xiàn)多線程編程
- Python中threading庫(kù)實(shí)現(xiàn)線程鎖與釋放鎖
- Python?threading和Thread模塊及線程的實(shí)現(xiàn)
相關(guān)文章
Python Pandas分組聚合的實(shí)現(xiàn)方法
這篇文章主要介紹了Python Pandas分組聚合的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07CentOS 7下Python 2.7升級(jí)至Python3.6.1的實(shí)戰(zhàn)教程
Centos是目前最為流行的Linux服務(wù)器系統(tǒng),其默認(rèn)的Python 2.x,這篇文章主要給大家分享了關(guān)于在CentOS 7下Python 2.7升級(jí)至Python3.6.1的實(shí)戰(zhàn)教程,文中將升級(jí)的步驟一步步的介紹的非常詳細(xì),對(duì)大家的理解和學(xué)習(xí)具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-07-07對(duì)python中的控制條件、循環(huán)和跳出詳解
今天小編就為大家分享一篇對(duì)python中的控制條件、循環(huán)和跳出詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06