我正在使用一个简单的上下文管理器,其中包含一个异步循环:
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 对象时,出现“Coroutine was never waiting”错误。
with Runner() as r:
r.do_work()
with Runner() as r2:
r2.do_work()
因为第一个 Runner(r) 中的循环已闭合。如果我不关闭循环,一切都会正常exit,但我不需要保持它打开。我知道一个线程中只能有一个循环,但为什么它不等待 run_until_complete 呢?
为什么它不等待 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())
Result:
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'test' was never awaited
如何解决这个问题?
由于您以这种方式使用事件循环,因此您可以使用 new事件循环 https://docs.python.org/3/library/asyncio-eventloops.html#asyncio.AbstractEventLoopPolicy.new_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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)