โดยทั่วไปวิธีการทำเช่นนี้จะใช้เธรดพูลและการดาวน์โหลดคิวซึ่งจะส่งสัญญาณหรือเหตุการณ์เมื่องานนั้นเสร็จสิ้นการประมวลผล คุณสามารถทำได้ภายในขอบเขตของโมดูลเธรดที่ Python มีให้
เพื่อดำเนินการกล่าวว่าผมจะใช้วัตถุเหตุการณ์และโมดูลคิว
อย่างไรก็ตามการสาธิตอย่างรวดเร็วและสกปรกเกี่ยวกับสิ่งที่คุณสามารถทำได้โดยใช้การใช้งานอย่างง่าย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()
สังเกตว่าไม่มีการตั้งค่าสถานะ daemon ที่นี่
import threading, time; wait=lambda: time.sleep(2); t=threading.Thread(target=wait); t.start(); print('end')
). ฉันหวังว่า "พื้นหลัง" ส่อเค้าแยกออกเช่นกัน