Python中使用asyncio实现异步IO实例分析

Evan
Evan
发布时间:2026-10-14 | 4人浏览过
原创

本文深入解析Python 3.4引入的asyncio标准库,阐述其基于消息循环的异步IO编程模型。通过EventLoop管理协程执行,并结合TCP回显客户端代码示例,展示如何利用asyncio实现高效网络通信,涵盖从底层连接处理到高层数据流原语的应用。

1、说明

在Python中实现异步IO操作十分便捷,asyncio作为Python 3.4版本引入的标准库,原生内置了对异步IO的支持。

asyncio的核心编程模型建立在消息循环之上。开发者需从asyncio模块获取EventLoop的引用,随后将待执行的协程提交至EventLoop中运行,以此完成异步IO的处理流程。

2、实例


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

知识点扩展:

数据流(Streams)

数据流(Streams)提供了一套高阶的异步/等待就绪(async/await-ready)原语,专门用于处理网络连接。它允许开发者在不依赖回调函数和底层传输协议的情况下,直接进行数据的发送与接收。

以下代码展示了如何使用asyncio构建一个TCP回显客户端:


import asyncio

async def tcp_echo_client(message):
  reader, writer = await asyncio.open_connection(
    '127.0.0.1', 8888)

  print(f'Send: {message!r}')
  writer.write(message.encode())

  data = await reader.read(100)
  print(f'Received: {data.decode()!r}')

  print('Close the connection')
  writer.close()
  await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))

至此,关于Python中使用asyncio实现异步IO的实例分析介绍完毕。如需了解更多相关内容,建议查阅本站往期文章或继续浏览后续教程,感谢大家的支持!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表