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

@本文來源於公衆號:csdn2299,喜歡可以關注公衆號 程序員學府
本文實例講述了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,工作了發現吃了計算機基礎不好的虧,學歷不行這是
沒辦法的事,只能後天彌補,於是在編碼之外開啓了自己的逆襲之路,不斷的學習python核心知識,深入的研習計算機基礎知識,整理好了,如果你也不甘平庸,那就與我一起在編碼之外,不斷成長吧!
其實這裏不僅有技術,更有那些技術之外的東西,比如,如何做一個精緻的程序員,而不是“屌絲”,程序員本身就是高貴的一種存在啊,難道不是嗎?[點擊加入]想做你自己想成爲高尚人,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章