Python 3.x 检查asyncio屏蔽协同路由是否运行

Python 3.x 检查asyncio屏蔽协同路由是否运行,python-3.x,python-asyncio,Python 3.x,Python Asyncio,如果我有以下代码示例 async def coro(): # Cancelled error could be raised here await asyncio.sleep(1) # Or here await asyncio.shield( another_coro() ) # Or here async def wait_on_it(loop): f = loop.create_task(coro()) #

如果我有以下代码示例

async def coro():
    # Cancelled error could be raised here
    await asyncio.sleep(1)
    # Or here
    await asyncio.shield(
        another_coro()
    )
    # Or here

async def wait_on_it(loop):
    f = loop.create_task(coro())
    # Pretend f may or may not happen, I just sleep in this example
    await asyncio.sleep(1)
    if not f.done():
        f.cancel() # Will raise CancelledError when some await finishes in coro()
如何确定屏蔽任务是否实际运行?我有重要的逻辑必须在屏蔽任务运行时运行。可能屏蔽该函数不是正确的方法?

coro()
可以通过修改从调用方接收的可变对象将信息传输给调用方:

class Ref:
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

async def coro(run_ref):
    await asyncio.sleep(1)
    run_ref.ran_another_coro = True
    await asyncio.shield(another_coro())

async def wait_on_it(loop):
    run_ref = Ref(ran_another_coro=False)
    f = loop.create_task(coro(run_ref))
    await asyncio.sleep(1)
    if not f.done():
        f.cancel()
    if run_ref.ran_another_coro:
         # ... another_coro() was started

由于
asyncio.shield
无法挂起,如果
等待它
观察到
run\u ref.ran\u other\u coro
的真实值,那么
other\u coro()
保证已经启动。

有什么理由定义类
ref
而不是简单地使用bool吗?@shane是的,bool是不可变的。在函数中赋值给
bool
只会修改局部变量,而不会修改调用者中的变量。另一方面,分配给调用者提供的可变对象的插槽将改变对象,这由
coro()
及其调用者都可以看到。