我需要从异步函数之外的 asyncio.create_task(function()) 返回一个值。
import asyncio
async def hello():
return("hello")
response = asyncio.get_event_loop().create_task(hello())
print(response)
这是输出的内容:
<Task pending coro=<hello() running at C:\Users\\PycharmProjects\PCWebsite\fjdfjd.py:3>>
当我想收到:
"Hello"
请注意,我不能使用 .run()
RuntimeError: asyncio.run() cannot be called from a running event loop
或 run_until_complete 当我收到错误时
RuntimeError: This event loop is already running
最佳答案
根据asyncio.create_task记录函数返回 Task
目的。
asyncio.create_task(coro, *, name=None)
Wrap the coro coroutine into a Task and schedule its execution. Return the Task object.
您可以使用 Task通过调用函数
task.result()
从任务本身提取结果(和一些其他信息)的函数当结果准备好时(任务完成)。例子:
import asyncio
async def func1():
return 1233
loop = asyncio.get_event_loop()
task = loop.create_task(func1())
# The following line is needed so the loop will run and complete the task in the first place.
loop.run_until_complete(task)
结果与:
>>> task.done()
True
>>> task.result()
1233
关于python - 有没有办法让 asyncio.create_task 返回异步函数之外的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683558/