如何调试异步 python 代码?
How to debug async python code?
我最近在玩异步代码,当我尝试调试 PyCharm 中的代码时,我看到了一些非常奇怪的行为,我认为这是因为底层架构import asyncio。
这就是我正在谈论的代码。
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
这很奇怪,因为当我在协程中设置断点时,执行永远不会中断并且整个代码很容易完成 运行 除此之外,我没有得到太多事件循环的细节(除了堆栈中的一些混乱)。
这是我的问题
- 调试异步代码有什么标准或一些好的做法吗?
- 如何窥探事件循环的执行流程?
- 为什么它不在异步函数内部中断?
只是在这里添加示例:
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0) # add breakpoint here and then run it in debug mode
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
我最近在玩异步代码,当我尝试调试 PyCharm 中的代码时,我看到了一些非常奇怪的行为,我认为这是因为底层架构import asyncio。 这就是我正在谈论的代码。
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
这很奇怪,因为当我在协程中设置断点时,执行永远不会中断并且整个代码很容易完成 运行 除此之外,我没有得到太多事件循环的细节(除了堆栈中的一些混乱)。
这是我的问题
- 调试异步代码有什么标准或一些好的做法吗?
- 如何窥探事件循环的执行流程?
- 为什么它不在异步函数内部中断?
只是在这里添加示例:
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0) # add breakpoint here and then run it in debug mode
return x + y
tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()