gpt4 book ai didi

python - python 3.8的异步编程如何使用 'yield'语句?

转载 作者:行者123 更新时间:2023-12-05 02:56:23 25 4
gpt4 key购买 nike

在python的asyncio异步编程(3.7或以下版本)中,如果我想手动让协程将其控制权交还给主事件循环,我可以使用这段代码:

@asyncio.coroutine
def switch():
yield
return

async def task():
# ...do something
# ...
await switch() # then this coroutine will be suspended and other will be triggered
# ...
# ... do something else when it's triggered again.

但是在 python3.8 中,“@coroutine”装饰器已被弃用。此外,我不能在“async def”中使用 yield(因为它将定义一个异步生成器而不是协程)。那么如何实现相同的功能呢?

最佳答案

TLDR:不要使用明确的 yield 来切换协程。对于 asyncio,请改用 asyncio.sleep(0)


实际上,所有事件循环都将它们各自的 sleep 视为持续时间为 0 的意思是“让其他协程运行”。对于 asyncio,使用 asyncio.sleep(0) 让其他协程运行。

async def task():
# ...do something
# ...
await asyncio.sleep(0) # then this coroutine will be suspended and other will be triggered
# ...
# ... do something else when it's triggered again.

Sleeping (asyncio)

sleep() always suspends the current task, allowing other tasks to run.

Checkpoints (trio)

… it’s useful to know that await trio.sleep(0) is an idiomatic way to execute a checkpoint without doing anything else …

Time (curio)

Sleep for a specified number of seconds. If the number of seconds is 0, execution switches to the next ready task (if any).


如果出于某种原因需要对事件循环显式yield,请创建自定义类并在其__await__ 特殊方法中创建yield

class Switch:
"""Switch coroutines by yielding to the event loop"""
def __await__(self):
yield

请注意,这会向事件循环发送一个空的 None。事件循环是否以及如何处理此信号取决于所使用的异步库。

关于python - python 3.8的异步编程如何使用 'yield'语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60603096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com