gevent simple coroutine


import gevent
from gevent import monkey
monkey.patch_all()
import requests
import time
import os
import pprint

urls = ['http://www.baidu.com',
        'http://www.cnblogs.cn',
        'http://www.github.com']

dict_url_content = {}

def get_content(url):
    print url
    content = requests.get(url).content
    dict_url_content[url] = content
    os.system('ping %s' % url.replace('http://', ''))
    time.sleep(5)


start = time.time()
list_gevent = []
# signal thread: 33.003
for url in urls:
    # t = gevent.spawn(get_content, url)
    t = gevent.Greenlet(get_content, url)
    t.start()
    list_gevent.append(t)

gevent.joinall(list_gevent)

pprint.pprint(dict_url_content)

print time.time() - start


posted @ 2017-03-26 14:27  idlewith  阅读(182)  评论(0编辑  收藏  举报