Модуль eventlet.green.urllib2 не найден

Я пытаюсь запустить самый первый пример кода на http://eventlet.net/doc/examples.html, webcrawler.py:

#!/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 = [
    "https://www.google.com/intl/en_ALL/images/logo.gif",
    "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))

Однако это приводит к

ModuleNotFoundError: No module named 'urllib2'

Я использую Eventlet версии 0.21.0. Этот модуль перемещен в eventlet?

2 ответа

Примеры, похоже, устарели (а теперь даже больше).

Для Python 2 используйте это:

import eventlet
from eventlet.green import urllib2 as request

request.urlopen(...)

Для Python 3 используйте это:

import eventlet
from eventlet.green.urllib import request

request.urlopen(...)

Я наконец переключил свою систему сборки (в Sublime Editor) на Python 2 вместо Python 3. Теперь она работает как положено:

('opening', 'https://www.google.com/intl/en_ALL/images/logo.gif')
('opening', 'http://python.org/images/python-logo.gif')
('opening', 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif')
('done with', 'https://www.google.com/intl/en_ALL/images/logo.gif')
('got body from', 'https://www.google.com/intl/en_ALL/images/logo.gif', 'of length', 8558)
('done with', 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif')
('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)
[Finished in 0.8s]

Кстати, это показывает, что зеленые потоки работают асинхронно, как и предполагалось.

eventlet.green Пакет подражает иерархии модуля Python stdlib.

Python2 имеет модуль urllib2. В Python3 есть пакет urllib с подробными подмодулями.

Общая идея: увидеть нормальный код Python, изменить импорт блокирующих модулей с помощью eventlet.green версия или mod = eventlet.import_patched('mod') и наслаждаться.

Другие вопросы по тегам