पायथन 3.2 में शुरू, आप समांतर कार्यों को लॉन्च करने के लिए concurrent.futures
का उपयोग कर सकते हैं।
बाहर की जाँच करें इस ThreadPoolExecutor
उदाहरण:
http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example
यह सूत्र एचटीएमएल पुनः प्राप्त करने के spawns और प्रतिक्रियाओं पर काम करता है के रूप में वे प्राप्त कर रहे हैं।
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
उपरोक्त उदाहरण थ्रेडिंग का उपयोग करता है। वहाँ भी, एक समान ProcessPoolExecutor
प्रक्रियाओं की एक पूल का उपयोग करता है बल्कि धागे से:
http://docs.python.org/dev/library/concurrent.futures.html#processpoolexecutor-example
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
स्रोत
2011-02-10 23:32:20
वे ओवरकिल। मुझे बस एक स्क्रिप्ट के भीतर से एक साथ http कॉल की आवश्यकता है (मुझे कमांड लाइन से एक प्रक्रिया को कॉल करने की आवश्यकता नहीं है)। मुझे बस कॉलबैक कार्यक्षमता की आवश्यकता है लेकिन मुझे इसके लिए पाइथन में प्रक्रिया नहीं मिल रही है। आगे का शोध मुझे urllib2 की तरफ ले जा रहा है। – kasceled
ओवरकिल? थ्रेड के पास कमांड लाइन से कॉलिंग प्रक्रियाओं के साथ कुछ लेना देना नहीं है। – Falmarri
tippytop, हाँ निश्चित रूप से परिवहन के लिए urllib2 .. लेकिन आपको अभी भी समानांतर में उन्हें फेंकने की जरूरत है। तो आप थ्रेडिंग, मल्टीप्रोसेसिंग, समवर्ती। फ्यूचर्स, या एसिंच I/o आधारित समाधान कर सकते हैं। –