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

首頁 > 編程 > Python > 正文

python基于queue和threading實現多線程下載實例

2019-11-25 18:09:25
字體:
來源:轉載
供稿:網友

本文實例講述了python基于queue和threading實現多線程下載的方法,分享給大家供大家參考。具體方法如下:

主代碼如下:

  #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__中調用threading.Thread.__init__(self),
在run方法中實現耗時的操作

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'])#我的下載過程       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))

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德惠市| 江北区| 会同县| 芜湖县| 南木林县| 韶山市| 普宁市| 治县。| 贵德县| 闽侯县| 安阳县| 炉霍县| 石阡县| 中牟县| 海盐县| 葫芦岛市| 武平县| 土默特左旗| 大庆市| 太保市| 白玉县| 肃宁县| 柳江县| 博湖县| 潢川县| 鹿邑县| 上饶县| 渝北区| 济源市| 六安市| 禹城市| 岳阳县| 玉山县| 中超| 比如县| 连平县| 青海省| 和顺县| 罗江县| 金华市| 连云港市|