Typically, the way to do this is to use a thread pool and load the queue up, which will result in a signal, aka event, this task has completed processing. You can do this as part of the stream module that Python provides.
To perform these steps, I would use event objects and a Queue module .
However, a brief and dirty demonstration of what you can do using a simple threading.Thread implementation can be seen below:
import os import threading import time import urllib2 class ImageDownloader(threading.Thread): def __init__(self, function_that_downloads): threading.Thread.__init__(self) self.runnable = function_that_downloads self.daemon = True def run(self): self.runnable() def downloads(): with open('somefile.html', 'w+') as f: try: f.write(urllib2.urlopen('http://google.com').read()) except urllib2.HTTPError: f.write('sorry no dice') print 'hi there user' print 'how are you today?' thread = ImageDownloader(downloads) thread.start() while not os.path.exists('somefile.html'): print 'i am executing but the thread has started to download' time.sleep(1) print 'look ma, thread is not alive: ', thread.is_alive()
It might be wise not to question how I am doing the above. In this case, I would change the code to this:
import os import threading import time import urllib2 class ImageDownloader(threading.Thread): def __init__(self, function_that_downloads): threading.Thread.__init__(self) self.runnable = function_that_downloads def run(self): self.runnable() def downloads(): with open('somefile.html', 'w+') as f: try: f.write(urllib2.urlopen('http://google.com').read()) except urllib2.HTTPError: f.write('sorry no dice') print 'hi there user' print 'how are you today?' thread = ImageDownloader(downloads) thread.start()
Please note that the daemon flag is not set here.
Mahmoud Abdelkader Aug 23 2018-11-23T00: 00Z
source share