python-利用queue和threading实现多线程下载
2012-05-30 17:59
489 查看
主代码:
downloadworkers.py
类继承 threading.Thread,重载run方法..在__init__中调用threading.Thread.__init__(self),
在run方法中实现耗时的操作
#---------------------------------------------------- #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基于queue和threading实现多线程下载实例
- python基于queue和threading实现多线程下载实例
- Python 使用threading+Queue实现线程池
- python 线程简单使用----1利用threading 实现多线程
- selenium2 python自动化测试之利用AutoIt工具实现本地文件上传
- 利用python实现简单登陆注册系统
- 利用shell + python + expect实现类似xshell功能(测试环境:ubuntu)
- 利用google的API获取世界城市经纬度(python实现)
- python利用inotify实现把nginx日志实时写入数据库
- 利用 Python 实现多线程多任务提交 - matlab 函数示例
- python中的进程、线程(threading、multiprocessing、Queue、subprocess)
- Python:使用threading模块实现多线程(转)
- Python中利用函数装饰器实现备忘功能
- python利用selenium获取cookie实现免登陆
- 利用Python实现google瓦片转Arcgis瓦片
- 【Python】利用setdefault函数实现dict的转置(key与value对互换),统计value出现的次数
- python之利用PIL库实现页面的图片验证码及缩略图 推荐
- 利用python实现简单的爬虫
- 利用python 实现简单 爬虫
- python threading 模块来实现多线程