我想在一个Python协程中使用ThreadPoolExecutor,将一些阻塞的网络调用委托给一个单独的线程。然而,运行以下代码:
from concurrent.futures import ThreadPoolExecutor
import asyncio
def work():
# do some blocking io
pass
async def main():
executor = ThreadPoolExecutor()
await executor.submit(work)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
引起错误:
TypeError: object Future can't be used in 'await' expression
Future
对象不能被await吗?为什么会这样说?
我该如何await一个由executor.submit
返回的Future
对象?
Python 3.5.0
编辑
使用executor.submit
不是我的决定。这在多个库中被内部使用,例如requests-futures
。我正在寻找一种从协程中与这些模块进行交互的方法。
concurrent.futures.Future
不可等待。你可能想要使用的是asyncio.Future
。 - Jashandeep Sohiasyncio.wrap_future
可能是你正在寻找的。虽然我不确定它是否公开或在文档中列出。 - Jashandeep Sohi