python基于queue和threading實現(xiàn)多線程下載實例
本文實例講述了python基于queue和threading實現(xiàn)多線程下載的方法,分享給大家供大家參考。具體方法如下:
主代碼如下:
#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__中調(diào)用threading.Thread.__init__(self),
在run方法中實現(xiàn)耗時的操作
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程序設(shè)計有所幫助。
- Python中多線程thread與threading的實現(xiàn)方法
- Python用threading實現(xiàn)多線程詳解
- python使用threading獲取線程函數(shù)返回值的實現(xiàn)方法
- Python 使用threading+Queue實現(xiàn)線程池示例
- Python線程協(xié)作threading.Condition實現(xiàn)過程解析
- Python3 socket即時通訊腳本實現(xiàn)代碼實例(threading多線程)
- python中threading和queue庫實現(xiàn)多線程編程
- Python中threading庫實現(xiàn)線程鎖與釋放鎖
- Python?threading和Thread模塊及線程的實現(xiàn)
相關(guān)文章
學(xué)習(xí)Python selenium自動化網(wǎng)頁抓取器
本篇文章給大家介紹了Python selenium自動化網(wǎng)頁抓取器的實例應(yīng)用以及知識點分析,有需要的參考學(xué)習(xí)下。2018-01-01
Python中使用PyHook監(jiān)聽鼠標和鍵盤事件實例
這篇文章主要介紹了Python中使用PyHook監(jiān)聽鼠標和鍵盤事件實例,這個庫依賴于另一個Python庫PyWin32,并且只能運行在Windows平臺,需要的朋友可以參考下2014-07-07
python rolling regression. 使用 Python 實現(xiàn)滾動回歸操作
這篇文章主要介紹了python rolling regression. 使用 Python 實現(xiàn)滾動回歸操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Linux上安裝Python的PIL和Pillow庫處理圖片的實例教程
這里我們來看一下在Linux上安裝Python的PIL和Pillow庫處理圖片的實例教程,包括一個使用Pillow庫實現(xiàn)批量轉(zhuǎn)換圖片的例子:2016-06-06
Python調(diào)用ollama本地大模型進行批量識別PDF
現(xiàn)在市場上有很多PDF文件的識別,然而隨著AI的興起,本地大模型的部署,這些成為一種很方便的方法,本文我們就來看看Python如何調(diào)用ollama本地大模型進行PDF相關(guān)操作吧2025-03-03

