Python 与urllib2或其他http库的多个(异步)连接?

Python 与urllib2或其他http库的多个(异步)连接?,python,asynchronous,urllib2,python-2.5,Python,Asynchronous,Urllib2,Python 2.5,我有这样的代码 for p in range(1,1000): result = False while result is False: ret = urllib2.Request('http://server/?'+str(p)) try: result = process(urllib2.urlopen(ret).read()) except (urllib2.HTTPError, urllib2.UR

我有这样的代码

for p in range(1,1000):
    result = False
    while result is False:
        ret = urllib2.Request('http://server/?'+str(p))
        try:
            result = process(urllib2.urlopen(ret).read())
        except (urllib2.HTTPError, urllib2.URLError):
            pass
    results.append(result)
我想同时提出两个或三个要求,以加快这一进程。我可以使用urllib2吗?如何使用?如果没有,我应该使用哪个图书馆?谢谢。

要么你弄明白了,要么你()。

看看-一个基于协同程序的Python网络库,它使用greenlet在libevent循环之上提供高级同步API

例如:

#!/usr/bin/python
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details.

"""Spawn multiple workers and wait for them to complete"""

urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']

import gevent
from gevent import monkey

# patches stdlib (including socket and ssl modules) to cooperate with other greenlets
monkey.patch_all()

import urllib2


def print_head(url):
    print 'Starting %s' % url
    data = urllib2.urlopen(url).read()
    print '%s: %s bytes: %r' % (url, len(data), data[:50])

jobs = [gevent.spawn(print_head, url) for url in urls]

gevent.joinall(jobs)
也许使用和划分你的工作在2个进程左右

下面是一个示例(未经测试)


您可以使用异步IO来实现这一点

+=

GRequests允许您将请求与Gevent一起使用,以轻松地生成异步HTTP请求

import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)
grequests.map(rs)

我知道这个问题有点老了,但我认为推广另一个基于请求库构建的异步解决方案可能会有用

请求列表=['http://moop.com', 'http://doop.com', ...]
从简单请求导入请求
对于Requests().swarm中的响应(请求列表):
打印响应内容

文档在这里:

因此,基于协程的库具有这两者的优点,并且比线程和Twisted更简单:gevent、eventlet、concurrenceThreading是正确的答案,而不是像Twisted这样复杂的分层功能。我会使用线程而不是多处理;基于进程的多处理模块仅用于CPU绑定的任务,而不是此I/O绑定的任务。您能否详细说明如何传递函数来处理响应?医生似乎没有提到it@Overdrivr您可以使用示例:
grequests.get(u,hooks=dict(response=print\u url))
或者您可以使用
grequests.get(u,callback=print\u url)
import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)
grequests.map(rs)