国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python基于queue和threading實(shí)現(xiàn)多線程下載實(shí)例

2020-02-23 05:54:41
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(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
類(lèi)繼承 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ì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 岢岚县| 德州市| 平昌县| 新疆| 耿马| 乳源| 安陆市| 海晏县| 北流市| 平阴县| 宜州市| 新竹县| 苍梧县| 黄浦区| 玉门市| 南丰县| 长阳| 宽城| 镇康县| 丹阳市| 延吉市| 河东区| 旅游| 临西县| 蕲春县| 台东县| 岳西县| 汪清县| 江西省| 西乡县| 霍邱县| 修文县| 肃南| 阳曲县| 利津县| 乌审旗| 二连浩特市| 乳源| 台山市| 抚远县| 特克斯县|