zoukankan      html  css  js  c++  java
  • 协程补充

    协程举例

    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)

  • 相关阅读:
    洛谷P1762 偶数
    复习1
    zoj3329 One Person Game
    poj2096 Collecting Bugs
    hdu4035 Maze
    Cogs 2856. [洛谷U14475]部落冲突
    洛谷P2474 [SCOI2008]天平
    洛谷P3802 小魔女帕琪
    清北刷题冲刺 11-03 p.m
    清北刷题冲刺 11-03 a.m
  • 原文地址:https://www.cnblogs.com/Erick-L/p/7707961.html
Copyright © 2011-2022 走看看