本文实例讲述了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:
printconfig['log'], '%s\t%s' % (md5, 'failed')
except Exception, e:
printconfig['log'], '%s\t%s' % (md5, str(e))
希望本文所述对大家的Python程序设计有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“python基于queue和threading实现多线程下载实例”评论...
更新动态
2025年10月29日
2025年10月29日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]