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.

转载于:https://www.cnblogs.com/lovesKey/p/11192515.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值