python基于queue和threading实现多线程下载实例

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

hmac模块生成加入了密钥的消息摘要详解

hmac模块生成加入了密钥的消息摘要详解

hmac模块 hmac模块用于生成HMAC码。这个HMAC码可以用于验证消息的完整性,其原理也很简单,就是一种加入了密钥的消息摘要,相比起MAC更加安全。JWT(JSON Web Tok...

python实现操作文件(文件夹)

本文实例为大家分享了pyhton操作文件的具体代码,供大家参考,具体内容如下 copy_file 功能:将某个文件夹下的所有文件(文件夹)复制到另一个文件夹 #! python 3...

Python的Flask框架中配置多个子域名的方法讲解

Flask子域名 一般用于数量比较少的子域名,一个模块对应一个子域名。先看下面一个例子: modules.py: from flask import Blueprint publi...

pygame播放音乐的方法

本文实例讲述了pygame播放音乐的方法。分享给大家供大家参考。具体如下: 方法一: import pygame filename='/home/A.mp3' pygame.mixe...

Pandas中Series和DataFrame的索引实现

正文 在对Series对象和DataFrame对象进行索引的时候要明确这么一个概念:是使用下标进行索引,还是使用关键字进行索引。比如list进行索引的时候使用的是下标,而dict索引的时...