In der Regel besteht die Möglichkeit hierfür darin, einen Thread-Pool und Warteschlangen-Downloads zu verwenden, die ein Signal (auch als Ereignis bezeichnet) ausgeben, wenn die Verarbeitung dieser Aufgabe abgeschlossen ist. Sie können dies im Rahmen des von Python bereitgestellten Threading-Moduls tun .
Um diese Aktionen auszuführen, würde ich Ereignisobjekte und das Warteschlangenmodul verwenden .
Eine schnelle und schmutzige Demonstration dessen, was Sie mit einer einfachen threading.ThreadImplementierung tun können, finden Sie unten:
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()
Es wäre wahrscheinlich sinnvoll, nicht wie oben zu wählen. In diesem Fall würde ich den Code folgendermaßen ändern:
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()
thread.join()
Beachten Sie, dass hier kein Daemon-Flag gesetzt ist.
import threading, time; wait=lambda: time.sleep(2); t=threading.Thread(target=wait); t.start(); print('end')). Ich hatte gehofft, dass "Hintergrund" auch losgelöst impliziert.