【发布时间】:2015-08-17 21:08:19
【问题描述】:
如何异步插入任务以在另一个线程中运行的asyncio 事件循环中运行?
我的动机是在解释器中支持交互式异步工作负载。我无法阻止主 REPL 线程。
示例
我目前有缺陷的理解说以下应该有效。为什么不呢?实现上述目标的更好方法是什么?
import asyncio
from threading import Thread
loop = asyncio.new_event_loop()
def f(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
t = Thread(target=f, args=(loop,))
t.start()
@asyncio.coroutine
def g():
yield from asyncio.sleep(1)
print('Hello, world!')
asyncio.async(g(), loop=loop)
【问题讨论】:
标签: python python-asyncio