簡體   English   中英

使用python多線程下載循環

[英]Multi-thread a download loop with python

我有一份清單。

symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'rx', 'jnj', 'osip')

URL = "http://www.Xxxx_symbol=%s"

def fetch(symbols):
    try:
        url = URL % '+'.join(symbols)
        fp = urllib2.urlopen(url)
        try:
            data = fp.read()

        finally:
            fp.close()
        return data
    except Exception as e:
        print "No Internet Access" 

我試圖多線程(有4個線程)獲取進程,而不是多進程而不是使用twisted。 Url fetch的輸出文件是csv,有7行標題信息,我想擺脫它。 我想將每個符號循環到它自己的文件中。 之前我使用過這個獲取代碼。 我可以得到一個有一個元素的符號列表。

這應該讓你開始:

from threading import Thread, Lock

data = {}
data_lock = Lock()

class Fetcher(Thread):
    def __init__(self, symbol):
        super(Thread, self).__init__()
        Thread.__init__(self)
        self.symbol = symbol

    def run(self):
        # put the code from fetch() here
        # replace 'data = fp.read()' with the following
        tmp = fp.read()
        data_lock.acquire()
        data[self.symbol] = tmp
        data_lock.release()

# Start a new Fetcher thread like this:
fetcher = Fetcher(symbol)
fetcher.start()
# To wait for the thread to finish, use Thread.join():
fetcher.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM