协程补充

协程举例

from gevent import monkey;monkey.patch_all()
import gevent
import requests
import time

def runtask(url):
    print('visit --> %s %s' % (url,time.ctime()))
    try:
        res = requests.get(url)
        time.sleep(2)
        data = res.text
        print('%d bytes received from %s %s' % (len(data),url,time.ctime()))
    except Exception as e :
        print(e)

if __name__ == '__main__':
    urls = ['http://www.baidu.com','http://www.sohu.com','http://www.163.com']
    greenlets = [ gevent.spawn(runtask,url) for url in urls]
    gevent.joinall(greenlets)

result

协程池

from gevent import monkey;monkey.patch_all()
from gevent.pool import Pool
import requests
import time

def runtask(url):
    print('visit --> %s %s' % (url,time.ctime()))
    try:
        res = requests.get(url)
        time.sleep(2)
        data = res.text
        print('%d bytes received from %s %s' % (len(data),url,time.ctime()))
    except Exception as e :
        print(e)
    return 'url %s --->finshed' % url

if __name__ == '__main__':
    pool = Pool(2)
    urls = ['http://www.baidu.com','http://www.sohu.com','http://www.163.com']
    results = pool.map(runtask,urls)
    print(results)

 

posted @ 2017-10-22 10:25  Erick-LONG  阅读(117)  评论(0编辑  收藏  举报