Multithreaded download loop with python

I have a list.

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" 

I am trying a multi-threaded (with 4 threads) sampling process, not a multi-processor one and not using twisted. Url fetch - csv output file with 7 lines of header information I want to get rid of. I would like to loop each character in my own file. I used to use this code. I can get a list of characters that has one item.

+3
source share
1 answer

This should help you:

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()
+4
source

Source: https://habr.com/ru/post/1789129/


All Articles