आमतौर पर ऐसा करने का तरीका थ्रेड पूल और कतार डाउनलोड का उपयोग करना होगा जो एक संकेत जारी करेगा, एक घटना, उर्फ एक घटना, जब उस कार्य ने प्रसंस्करण समाप्त कर दिया है। आप ऐसा कर सकते हैं थ्रेडिंग मॉड्यूल के दायरे में पायथन प्रदान करता है।
उक्त कार्यों को करने के लिए, मैं इवेंट ऑब्जेक्ट्स और क्यू मॉड्यूल का उपयोग करूंगा ।
हालाँकि, एक सरल threading.Threadकार्यान्वयन का उपयोग करके आप जो कर सकते हैं उसका एक त्वरित और गंदा प्रदर्शन नीचे देखा जा सकता है:
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()
यह शायद समझ में नहीं आता है कि मैं चुनाव नहीं कर रहा हूं जैसा कि मैं ऊपर कर रहा हूं। किस स्थिति में, मैं इस कोड को बदलूंगा:
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()
ध्यान दें कि यहां कोई डेमॉन फ्लैग सेट नहीं है।
import threading, time; wait=lambda: time.sleep(2); t=threading.Thread(target=wait); t.start(); print('end'))। मैं उम्मीद कर रहा था "पृष्ठभूमि" के रूप में अच्छी तरह से अलग अलग निहित है।