[英]Calling Tornado Coroutine from asyncio
我的主事件循環使用 asyncio 但需要調用一個類型為tornado.concurrent.Future
的協程的庫方法。 嘗試等待協程失敗並出現RuntimeError
。
RuntimeError: Task got bad yield: <tornado.concurrent.Future object at 0x7f374abdbef0>
文檔和搜索建議升級 Tornado 的版本(當前使用 4.5)或使用不再產生RuntimeError
而是掛在await
上的方法tornado.platform.asyncio.to_asyncio_future
。 我很想知道是否有人可以解釋發生了什么。 有兩種主要方法,一種是使用 asyncio 調用 Tornado 協程,另一種是純 Tornado,它按預期工作。
import asyncio
from tornado import gen
from tornado.platform.asyncio import to_asyncio_future
async def coro_wrap():
tornado_fut = coro()
print(f'tornado_fut = {tornado_fut}, type({type(tornado_fut)})')
async_fut = to_asyncio_future(tornado_fut)
print(f'async_fut = {async_fut}')
res = await async_fut
print(f'done => {res}')
@gen.coroutine
def coro():
print('coro start')
yield gen.sleep(3)
print('coro end')
return 'my result'
def main():
loop = asyncio.get_event_loop()
task = loop.create_task(coro_wrap())
loop.run_until_complete(task)
print('end')
def main2():
from tornado import ioloop
loop = ioloop.IOLoop()
res = loop.run_sync(coro)
print(res)
if __name__ == '__main__':
main()
Output 從主
coro start
tornado_fut = <tornado.concurrent.Future object at 0x7f41493f1f28>, type(<class 'tornado.concurrent.Future'>)
async_fut = <Future pending>
Output 來自 main2
coro start
coro end
my result
在新版本的 Tornado 中,這很有效。
在舊版本的龍卷風中,您必須同時使用to_asyncio_future
並在啟動時調用tornado.platform.asyncio.AsyncIOMainLoop.install()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.