我在理解如何将新任务挂起到已经运行的事件循环时遇到了问题.
这段代码:
@H_403_4@import asyncio import logging @asyncio.coroutine def blocking(cmd): while True: logging.info("in blocking coroutine") yield from asyncio.sleep(0.01) print("ping") def main(): logging.info("in main funciton") loop = asyncio.get_event_loop() logging.info("new loop created") logging.info("loop running forever") loop.run_forever() asyncio.async(blocking("ls")) logging.basicConfig(level = logging.INFO) main()将run_forever()更改为run_until_complete(asyncio.async(blocking(“ls”))工作正常.但我真的很困惑 – 为什么我不能在已经运行的循环上挂起任务?
解决方法
问题是对loop.run_forever()的调用阻塞;它启动事件循环,直到你明确地停止循环才会返回 – 因此是run_forever的永远部分.您的程序从不显式停止事件循环,因此永远不会达到您的asyncio.async(blocking(“ls”))调用.
使用asyncio.async将新任务添加到已经运行的循环中是很好的,您只需要确保该函数实际上是从事件循环内的协同程序或回调内部调用的.这里有些例子:
安排阻止在事件循环开始后立即运行:
@H_403_4@def main(): logging.info("in main funciton") loop = asyncio.get_event_loop() logging.info("new loop created") logging.info("loop running forever") asyncio.async(blocking("ls")) loop.run_forever()安排阻止事件循环执行的回调:
@H_403_4@def start_blocking(): asyncio.async(blocking("ls")) def main(): logging.info("in main funciton") loop = asyncio.get_event_loop() logging.info("new loop created") logging.info("loop running forever") loop.call_soon(start_blocking) # Calls start_blocking once the event loop starts loop.run_forever()