我观察到asyncio.run_coroutine_threadsafe
函数不接受一般的可等待对象,我不明白这种限制的原因。观察
import asyncio
async def native_coro():
return
@asyncio.coroutine
def generator_based_coro():
return
class Awaitable:
def __await__(self):
return asyncio.Future()
loop = asyncio.get_event_loop()
asyncio.run_coroutine_threadsafe(native_coro(), loop)
asyncio.run_coroutine_threadsafe(generator_based_coro(), loop)
asyncio.run_coroutine_threadsafe(Awaitable(), loop)
使用 Python 3.6.6 运行它会产生结果
Traceback (most recent call last):
File "awaitable.py", line 24, in <module>
asyncio.run_coroutine_threadsafe(Awaitable(), loop)
File "~/.local/python3.6/lib/python3.6/asyncio/tasks.py", line 714, in run_coroutine_threadsafe
raise TypeError('A coroutine object is required')
TypeError: A coroutine object is required
其中第 24 行是asyncio.run_coroutine_threadsafe(Awaitable(), loop)
.
我知道我可以将可等待对象包装在定义如下的协程中
awaitable = Awaitable()
async def wrapper():
return await awaitable
asyncio.run_coroutine_threadsafe(wrapper(), loop)
然而我的期望是等待将是直接有效的论点run_coroutine_threadsafe
.
我的问题是:
- 这个限制的原因是什么?
- Is the
wrapper
上面定义的函数是传递可等待的最传统方法run_coroutine_threadsafe
以及其他需要的 APIasync def
或者生成器定义的协程?