Python 3.2以降では、並列タスクの起動にconcurrent.futures
を使用できます。
チェックアウトこのThreadPoolExecutor
例は:
http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example
これは、HTMLを取得するためのスレッドを生成し、それらが受信される応答に作用します。
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)))
Way Overkill。私が必要とするのは、スクリプト内からの同時のhttp呼び出しです(コマンドラインなどからプロセスを呼び出す必要はありません)。私は単にコールバック機能を持っている必要がありますが、私はこれをPythonで見つけることができません。さらなる研究が私にurllib2を導いています。 – kasceled
オーバーキル?スレッドは、コマンドラインからプロセスを呼び出すこととは関係ありません。 – Falmarri
tippytop、もちろん、輸送用のurllib2 ..しかしあなたはまだそれを並行してスポーンする必要があります。スレッド化、マルチプロセッシング、concurrent.futures、またはasynch i/oベースのソリューションを実行できます。 –