我正在使用一个带有内部异步循环的简单上下文管理器:
class Runner:
def __init__(self):
self.loop = asyncio.get_event_loop()
def __enter__(self):
return self
def __exit__(self, *args):
self.loop.close()
def do_work(self):
...
return self.loop.run_until_complete(asyncio.gather(*futures))
当我使用两个Runner对象时,出现“从未等待协程”错误。
with Runner() as r:
r.do_work()
with Runner() as r2:
r2.do_work()
因为在第一个Runner(r)中关闭了循环。如果我没有在 exit 中关闭循环,则一切正常,但是我不需要保持打开状态。我知道我们在一个线程中只能有一个循环,但是为什么它不等待run_until_complete?
答案 0 :(得分:0)
为什么不等待run_until_complete
可能会发生以下情况:
import asyncio
async def test():
await asyncio.sleep(0.1)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
loop.close()
loop.run_until_complete(test())
结果:
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'test' was never awaited
由于您是通过这种方式使用事件循环的,因此每次只能使用新的event loop:
class Runner:
def __init__(self):
self.loop = asyncio.new_event_loop() # *new*_event_loop
def do_work(self):
# Make sure all futures are created
# with relevant event loop been set as current
asyncio.set_event_loop(self.loop)
# ...
return self.loop.run_until_complete(asyncio.gather(*futures))