【发布时间】:2022-01-16 11:22:14
【问题描述】:
这段代码的目标是让它运行主函数,称为main_process(),直到结束的异步函数,称为finish_process(),将变量finish_state设置为True,并且循环不会重复一遍。
import asyncio
import time
condition = True
finish_state = False
x = 0
async def finish_process(finish_state):
finish_state = True
time.sleep(5)
return finish_state
async def main_process(condition,finish_state,x):
while condition == True:
finish_state = await asyncio.run(finish_process(finish_state))
x = x + 1
print(x)
#if(x > 10):
if(finish_state == True):
print("Termina!")
condition = False
asyncio.run(main_process(condition,finish_state,x))
我已经将异步函数调用的 await 放在另一个异步函数中,我不明白为什么它总是用 await 报错。
我认为用await 或旧的yield from 指示应该可以解决同时等待另一个函数的结果。
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'finish_process' was never awaited
【问题讨论】:
-
来自官方doc
asyncio.run:“当另一个异步事件循环在同一个线程中运行时,无法调用此函数。”
标签: python python-3.x asynchronous async-await python-asyncio