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
  • 相关阅读:
    uart协议--Verilog及仿真
    DC综合的流程
    modelsim将vcd文件转换成wlf文件并查看波形
    将系统盘还原成原来的普通u盘
    Ubuntu的操作命令
    gvim快捷键
    dc_shell环境下TCL语言的使用
    AHB总线学习
    Ubuntu文件共享
    Linux基础学习 | 目录及文件
  • 原文地址:https://www.cnblogs.com/1zhangwenjing/p/7748219.html
Copyright © 2011-2022 走看看