zoukankan      html  css  js  c++  java
  • asyncio

    asyncio是python3.4版本引入的标准库,直接内置了对异步IO的支持。

    asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,把需要执行的协程扔到EventLoop中执行,就实现了异步IO.

    import asyncio
    
    @asyncio.coroutine
    def wget(host):
        print('wget %s...' % host)
        connect = asyncio.open_connection(host, 80)
        reader, writer = yield from connect
        header = 'GET / HTTP/1.0
    Host: %s
    
    ' % host
        writer.write(header.encode('utf-8'))
        yield from writer.drain()
        while True:
            line = yield from reader.readline()
            if line == b'
    ':
                break
            print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
        # Ignore the body, close the socket
        writer.close()
    
    loop = asyncio.get_event_loop()
    tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

     yield from:在生成器gen中使用yield from subgen()时,subgen会获得控制权,把产出的值传给gen的调用方(这里为事件循环),即调用方可以控制subgen,与此同时gen会阻塞,等待subgen终止。

    yield from可用于简化for循环中的yield表达式,例如:

    def gen():
        for c in 'AB':
            yield c
        for i in range(1, 3):
            yield i
    
    list(gen())
    ['A', 'B', '1', '2']

    可以改写为:

    def gen():
        yield from 'AB'
        yield from range(1, 3)
        
    
    list(gen())
    ['A', 'B', '1', '2']
    如有疑问请联系我,写的不对的地方请联系我进行更改,感谢~ QQ:1968380831
  • 相关阅读:
    【文章阅读】计算机体系-计算机将代码编译和持续运行过程中需要考虑的问题,以及具体的实现原理讲解
    JAVA性能调试+JProfiler使用相关
    【2016.10.30】王国保卫战-安卓汉化版
    【2017.01.05】装系统教程
    【2016.11.10】百度云离线下载迅雷链接
    mongodb 杂记
    缓存使用思路
    分布式 vs 集群
    切面 aop 笔记
    前端
  • 原文地址:https://www.cnblogs.com/1zhangwenjing/p/7748219.html
Copyright © 2011-2022 走看看