考虑这个程序,其中mainloop和coroutine停止它实际上是由我正在使用的库实现的。
import asyncio
import signal
running = True
async def stop():
global running
print("setting false")
running = False
await asyncio.sleep(3)
print("reached end")
async def mainloop():
while running:
print("loop")
await asyncio.sleep(1)
def handle_signal():
loop.create_task(stop())
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, handle_signal)
loop.run_until_complete(mainloop())
loop.close()
当程序收到信号时,我需要调用stop coroutine来停止mainloop。虽然在使用asyncio.BaseEventLoop.create_task
安排停止协程时,它首先会停止主循环,停止事件循环并且停止协程无法完成:
$ ./test.py
loop
loop
loop
^Csetting false
Task was destroyed but it is pending!
task: <Task pending coro=<stop() done, defined at ./test.py:7> wait_for=<Future pending cb=[Task._wakeup()]>>
如何在使事件循环等到完成时将coroutine添加到正在运行的事件循环中?
答案 0 :(得分:1)
正如您所发现的那样,问题是事件循环只等待mainloop()
完成,stop()
待定,asyncio
正确抱怨。
如果handle_signal
和顶级代码在您的控制之下,您可以轻松替换循环,直到mainloop
完成循环,直到自定义协程完成。该协程将调用mainloop
,然后等待清理代码完成:
# ... omitted definition of mainloop() and stop()
# list of tasks that must be waited for before we can actually exit
_cleanup = []
async def run():
await mainloop()
# wait for all _cleanup tasks to finish
await asyncio.wait(_cleanup)
def handle_signal():
# schedule stop() to run, and also add it to the list of
# tasks run() must wait for before it is done
_cleanup.append(loop.create_task(stop()))
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, handle_signal)
loop.run_until_complete(run())
loop.close()
另一个不需要新run()
协程(但仍需要修改后的handle_signal
)的选项是在run_until_complete()
之后发出第二个mainloop
完成:
# handle_signal and _cleanup defined as above
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, handle_signal)
loop.run_until_complete(mainloop())
if _cleanup:
loop.run_until_complete(asyncio.wait(_cleanup))
loop.close()