我正在使用Visual Studio code (VSCode)调试器读取以下代码。
import asyncio
async def main():
print("OK Google. Wake me up in 1 seconds.")
await asyncio.sleep(1)
print("Wake up!")
if __name__ == "__main__":
asyncio.run(main(), debug=False)
我可以理解安排回调以使进程休眠一秒钟的程序的主要流程,但很难理解何时或在何处调用_run_until_complete_cb?
在执行主协程之后,通过将_stopping标志设置为True,调用此函数/回调来停止事件循环。但是,它最初是通过add_done_callback附加到Future类中的_callbacks内部属性的,或者在完成future后很快被调用。
def add_done_callback(self, fn, *, context=None):
"""Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is
scheduled with call_soon.
"""
if self._state != _PENDING:
self._loop.call_soon(fn, self, context=context)
else:
if context is None:
context = contextvars.copy_context()
self._callbacks.append((fn, context))
无论哪种情况,它都通过call_soon方法注册到事件循环中,并在最后的下一次迭代中调用。但目前,未来还没有完成上面的else子句。
我的问题是,将来在哪里或者什么时候完成对else子句的_run_until_complete_cb?由于VSCode调试器只是跳过或忽略在Future和Task实例上调用方法的代码行,因此流程直接跳到_run_until_complete_cb中的call_soon中。
在完成主协程之后到底发生了什么?有没有人有关于异步模块的清理过程来停止事件循环的任何想法或提示,或者有办法通过VSCode调试器来查看Future或Task的方法?
提前谢谢你!
发布于 2019-10-01 07:40:05
如果你正在尝试调试到asyncio,那么你想要set "justMyCode": true
in your launch.json
。这将使调试器跟踪第三方代码,包括stdlib。
https://stackoverflow.com/questions/58152617
复制相似问题