eventlet

eventlet
  eventlet是一个基于greenlet,面向网络应用,提供并发能力的库。
  eventlet可以使用pip install eventlet进行安装。eventlet实际上并不会改变开发者编写代码的方法,而是改变了代码的执行流程。开发者负责按照阻塞的风格编写代码,eventlet负责提供近似非阻塞I/O的性能。
  可以通过下面的例子理解eventlet(注意:此例子只能在Python2.x下运行,在Python3.x下运行会报错!):

#!/usr/bin/env python
"""
This is a simple web "crawler" that fetches a bunch of urls using a pool to
control the number of outbound connections. It has as many simultaneously open
connections as coroutines in the pool.

The prints in the body of the fetch function are there to demonstrate that the
requests are truly made in parallel.
"""
import eventlet
from eventlet.green import urllib2


urls = [
    "http://help.bing.microsoft.com//Images/icon_notes_color.svg",
    "http://python.org/images/python-logo.gif",
    "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif",
]


def fetch(url):
    print("opening", url)
    body = urllib2.urlopen(url).read()
    print("done with", url)
    return url, body


pool = eventlet.GreenPool(200)
for url, body in pool.imap(fetch, urls):
    print("got body from", url, "of length", len(body))

程序输出:

('opening', 'http://python.org/images/python-logo.gif')
('opening', 'http://help.bing.microsoft.com//Images/icon_notes_color.svg')
('opening', 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif')
('done with', 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif')
('done with', 'http://help.bing.microsoft.com//Images/icon_notes_color.svg')
('got body from', 'http://help.bing.microsoft.com//Images/icon_notes_color.svg', 'of length', 1082)
('done with', 'http://python.org/images/python-logo.gif')
('got body from', 'http://python.org/images/python-logo.gif', 'of length', 2549)
('got body from', 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif', 'of length', 1874)

参考资料:
  Example
  eventlet PyPI