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

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

本文深入解析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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。