• 技术文章 >Python技术 >Python基础教程

    python中使用asyncio实现异步IO

    小妮浅浅小妮浅浅2021-02-25 18:07:44原创5431

    1、说明

    Python实现异步IO非常简单,asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

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

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    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\r\nHost: %s\r\n\r\n' % host

        writer.write(header.encode('utf-8'))

        yield from writer.drain()

        while True:

            line = yield from reader.readline()

            if line == b'\r\n':

                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()

    以上就是python中使用asyncio实现异步IO的方法,希望能对大家有所帮助更多Python学习指路:python基础教程

    专题推荐:python asyncio 异步io
    上一篇:python协程的两大优势 下一篇:Python列表常见操作总结

    相关文章推荐

    • Python中pickle模块的使用注意• python中条件判断分为哪几类?• Python hash对象的属性有哪些• python中if嵌套命令如何理解?• python异步IO如何同时处理请求• python协程的两大优势

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网