À partir de Python 3.2, vous pouvez utiliser concurrent.futures
pour lancer des tâches parallèles.
Vérifiez cette exemple ThreadPoolExecutor
:
http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example
Il engendre des fils pour récupérer HTML et agit sur les réponses qu'ils sont reçus.
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)))
L'exemple ci-dessus utilise le filetage. Il y a aussi un ProcessPoolExecutor
similaire qui utilise un pool de processus, plutôt que des fils:
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)))
De manière excessive. Tout ce dont j'ai besoin, ce sont des appels HTTP simultanés depuis un script (je n'ai pas besoin d'appeler un processus depuis la ligne de commande, etc). J'ai simplement besoin d'une fonctionnalité de rappel, mais je ne trouve pas le processus pour cela en python. D'autres recherches me mènent vers urllib2. – kasceled
Overkill? Les threads n'ont rien à voir avec l'appel de processus à partir de la ligne de commande. – Falmarri
tippytop, oui bien sûr urllib2 pour le transport .. mais vous avez encore besoin de les engendrer en parallèle. Vous pouvez donc faire du threading, du multiprocessing, du concurrent.futures ou une solution basée sur les E/S asynch. –