Python 协程的回溯

ado*_*ntz 5 coroutine python-3.x python-asyncio

假设我有以下代码:

from types import coroutine

@coroutine
def stop():
    yield 1

async def test2():
    await stop()

async def test1():
    await test2()
    await test2() # Here
    await test2()

coro = test1()
coro.send(None)
coro.send(None)
Run Code Online (Sandbox Code Playgroud)

如何获得当前协程状态的回溯(回溯对象),即标有注释的行,而不人为地抛出不需要的异常?

Mik*_*mov 2

使用 oftraceback.print_stack()将为您提供与抛出异常完全相同的回溯:

async def test1():
    await test2()

    traceback.print_stack()
    # raise Exception()

    await test2() # Here
    await test2()
Run Code Online (Sandbox Code Playgroud)

如果您想接收对象而不是打印,可以使用traceback.extract_stack() 。


但请注意,您正在做一些奇怪的事情。asyncio协程不应该使用它的生成器的本质函数(例如.send().

asyncio您等待协程并使用事件循环运行顶级协程。请参阅文档中的操作方式。

asyncio我写了另一个小例子,展示了当您使用常规方式时如何在内部协程中打印 start :

import asyncio
import traceback


async def test3():
    traceback.print_stack()


async def test2():
    await test3()


async def test1():
    await test2()


asyncio.run(test1())
Run Code Online (Sandbox Code Playgroud)

你会看到的:

  File "C:\main.py", line 24, in <module>
    asyncio.run(test1())

  # inner event loop stack here

  File "C:\main.py", line 21, in test1
    await test2()
  File "C:\main.py", line 17, in test2
    await test3()
  File "C:\main.py", line 13, in test3
    traceback.print_stack()
Run Code Online (Sandbox Code Playgroud)