python异步

本文介绍了Python异步编程的基础知识,包括协程的概念、如何使用asyncio模块创建和管理异步任务,以及异步编程的基本原理。同时,文章还探讨了协程函数与协程对象的区别,并通过示例代码展示了如何实现异步任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 已完成:logging模块的学习
  • 接下来的目标:分为两步——要做什么和怎么做
  • requests模块的学习
  • python程序debug的方式
  • 异步
  • 网络的基本知识(做什么)

asnycio basic

https://pymotw.com/3/asyncio/index.html
app: <=interact=> event loop:

coroutines:

  • special functions that give up control to the caller without losing their state
    Q: a class-based abstraction layer for protocols and transports for writing code using callbacks instead of writing coroutines directly.

“coroutine”的两种含义:函数和对象

  • The function that defines a coroutine==a coroutine function (iscoroutinefunction() returns True).

  • The object obtained by calling a coroutine function==a coroutine object (iscoroutine() returns True).


Things a coroutine can do:

  • result = await future or result = yield from future
    • suspends the coroutine until the future is done, then returns the future’s result, or raises an exception, which will be propagated. (If the future is cancelled, it will raise a CancelledError exception.)
    • tasks ==futures
  • result = await coroutine or result = yield from coroutine
    • wait for another coroutine to produce a result
    • return expression
    • raise exception

运行cotouring

  • Call != start
  • schedule its execution.
    • await or yield from
    • ensure_future() function or AbstractEventLoop.create_task() method.
import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

**协程上下文切换**
Coroutines (and tasks) can only run when the event loop is running.

future:

a data structure representing the result of work that has not been completed yet.

Task:

a subclass of Future that knows how to wrap and manage the execution for a coroutine.

https://pymotw.com/3/asyncio/coroutines.html
coroutine function-> coroutine object
coroutine object .send()->run function code


  1. 建立一个coroutine func
  2. 建立event loop or 实例化一个特定的eventloop
    run_until_complete():用asyncio来start一个协程
  3. 从coroutine建立新的coroutine await() context 转换?
  4. earlier Python 3 -> @asyncio + yield from
  5. now: async def + await
python
@asyncio.coroutine()
def func()
    yield

Future

work not completed yet<-event loop watch for

  1. set_result(): change state
  2. await
### Python 异步编程概述 Python异步编程是一种高效的并发模型,适用于 IO 密集型任务。其核心概念基于协程(coroutines)、事件循环(event loop)以及异步/等待语法(`async` 和 `await`)。以下是关于如何使用 Python 进行异步编程的具体说明: --- #### 1. **协程的基础** 协程是 Python 中一种特殊的函数,可以通过 `async def` 定义[^2]。它们允许程序在遇到耗时操作(如网络请求或文件读写)时暂停执行,并让出控制权给事件循环。 示例代码如下: ```python import asyncio async def say_hello(): print("Hello, ") await asyncio.sleep(1) # 模拟耗时操作 print("World!") # 调用协程 asyncio.run(say_hello()) ``` 上述代码展示了如何定义并运行一个简单的协程。注意,在调用 `say_hello()` 函数前需加上 `await` 关键字以确保正确执行[^1]。 --- #### 2. **事件循环的作用** 事件循环负责管理多个协程之间的切换。当某个协程因阻塞操作而暂停时,事件循环会选择另一个准备就绪的协程继续执行。 以下是一个多任务的例子: ```python async def task(name, delay): for i in range(3): print(f"{name} is running... ({i})") await asyncio.sleep(delay) async def main(): tasks = [ asyncio.create_task(task("Task A", 1)), asyncio.create_task(task("Task B", 0.5)) ] await asyncio.gather(*tasks) asyncio.run(main()) ``` 在这个例子中,两个任务交替执行,体现了异步编程的优势——无需额外线程即可实现高效率的任务调度。 --- #### 3. **异步 HTTP 请求** 借助第三方库 `aiohttp` 可轻松完成异步网络请求。下面是一段完整的异步爬虫样例代码[^3]: ```python import aiohttp import asyncio async def fetch_url(session, url): async with session.get(url) as response: return await response.text() async def main(urls): async with aiohttp.ClientSession() as session: results = await asyncio.gather(*(fetch_url(session, url) for url in urls)) for idx, result in enumerate(results): print(f"Result {idx}: {result[:100]}") # 打印部分响应内容 urls = ["https://jsonplaceholder.typicode.com/posts"] * 3 asyncio.run(main(urls)) ``` 该脚本能够同时向多个 URL 发起请求,显著提高性能。 --- #### 4. **其他支持异步的框架** 除了标准库中的 `asyncio` 外,还有一些流行的第三方工具也提供了强大的异步功能,比如 Twisted、Tornado 等。这些框架通常用于构建高性能服务器应用。 --- ### 总结 通过掌握基本的协程机制和事件驱动原理,开发者可以在 Python 中高效处理大量并发任务。无论是开发 Web 应用还是数据抓取工具,异步编程都是一项不可或缺的技术技能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值