Spa*_*key 5 python python-asyncio
非常简单的代码:
async def poll():
await asyncio.sleep(1)
def caller(somefunction):
somefunction() # we don't know if callable is async or not
def main():
caller(poll) # how to pass an async function "poll" here?
Run Code Online (Sandbox Code Playgroud)
我想通过将其作为可调用/lambda 传递给“调用者”函数来调用“poll”。通常,在设计良好的语言中,例如 C#,您会这样做poll().Result,因为 poll() 返回一个任务,该任务具有 Wait() 和 Result 等方法来阻止和等待,或者如果您想阻止和等待并返回,您可以使用“await”到您当前所在异步方法的调用者。
当声明一个async函数然后调用它时,也需要等待它。与 一样await asyncio.sleep(1),您需要等待callee()。见下文:
import asyncio
async def callee():
await asyncio.sleep(1)
print ("first")
return 1
async def caller():
await callee() # how do I wait the result of this?
print("second")
async def main():
await caller()
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
- 编辑 -
要运行协程,您有 3 个选项asyncio。
await协程:你不希望/不能在同步函数中使用它asyncio.create_task(): 也需要在代码中的某个地方等待当您不等待选项 2 和 3 时,协程就不会执行。因此,您在这里尝试做的事情无法通过该asyncio包来实现。
我真正不明白的是为什么你想执行一个async函数来等待它同步?这违背了使用任务的目的。