zoukankan      html  css  js  c++  java
  • python的协程,monkeyPatch

    monkey patch 一般指运行时候进行动态替换.
    基本上我们使用gevent,会在最开头的地方加入gevent.monkey.patch_all();把标准库中的thread/socket等给替换掉.这样我们在后面使用socket的时候它会变成非阻塞的了.而我们却什么也不用做.

    一个案列

    
    from gevent import monkey; monkey.patch_all()
    import gevent
    from urllib import request
    
    
    
    def run_task(url):
        print("开始访问 --> %s" % url)
        try:
            response = request.urlopen(url)
            data = response.read()
            print("{} bytes received from {}".forma(len(data), url))
        except Exception:
            print("访问中出错了")
    
    if __name__ == '__main__':
        urls = ['https://baidu.com/', 'https://github.com','https://blog.csdn.net/', 'https://cnblogs.com/lovesKey']
        # 定义协程方法
        greenlets = [gevent.spawn(run_task, url) for url in urls]
        # 添加协程任务,并且启动运行
        gevent.joinall(greenlets)
    
    

    最快访问结束的会在第一位,最慢的会在最后一位.
    输出结果:

    Visit --> https://baidu.com/
    Visit --> https://github.com
    Visit --> https://blog.csdn.net/
    Visit --> https://cnblogs.com/lovesKey
    154097 bytes received from https://baidu.com/.
    26813 bytes received from https://cnblogs.com/lovesKey.
    155908 bytes received from https://blog.csdn.net/.
    86916 bytes received from https://github.com.
    
  • 相关阅读:
    xml 总结(一)数据岛,命名空间
    activiti designer 安装到 myeclipse
    activiti5.15 学习笔记
    goole网址IP
    form 中Enctype=multipart/form-data 的作用
    上传文件form表单enctype="multipart/form-data"传值解决办法(代原代码)
    淘宝初始化样式
    js闭包使用之处
    CSS Sprites
    iframe用的场景
  • 原文地址:https://www.cnblogs.com/lovesKey/p/11192515.html
Copyright © 2011-2022 走看看