asyncio.CancelledError 和“_GatheringFuture 异常从未检索到”的奇怪行为

python

1个回答

写回答

千琉

2025-07-06 20:20

+ 关注

Python
Python

使用 asyncio 模块进行异步编程时,有时会遇到一些奇怪的行为。其中两个常见的异常是 asyncio.CancelledError 和 "_GatheringFuture 异常从未检索到"。这些异常可能会导致程序出现问题,并且可能会导致程序无法正常运行。

在使用 asyncio 模块时,有时会遇到 asyncio.CancelledError 异常。这个异常通常发生在取消一个正在运行的协程时。当我们在运行一个协程时,如果我们在协程运行期间取消了它,就会抛出 asyncio.CancelledError 异常。这个异常可以通过在协程中使用 try-except 块来捕获和处理。通常,我们可以在 except 块中执行一些清理操作,然后退出协程。

另一个常见的异常是 "_GatheringFuture 异常从未检索到"。这个异常通常发生在我们使用 asyncio.gather() 函数来等待多个协程完成时。当我们使用 asyncio.gather() 函数等待一组协程时,如果其中一个协程抛出了异常并且我们没有处理这个异常,就会出现 "_GatheringFuture 异常从未检索到" 的错误。这个异常的原因是我们没有对异常进行处理,导致 asyncio.gather() 函数无法正确返回结果。

在处理这两个异常时,我们可以采取一些措施来解决问题。首先,对于 asyncio.CancelledError 异常,我们可以在协程中使用 try-except 块来捕获并处理这个异常。在处理异常时,我们可以执行一些清理操作,然后退出协程。这样可以确保程序能够正常退出,并避免出现一些意外的行为。

对于 "_GatheringFuture 异常从未检索到",我们可以使用 asyncio.ensure_future() 函数来确保我们对每个协程的异常都进行处理。通过使用 asyncio.ensure_future() 函数,我们可以将每个协程包装成一个 Future 对象,并在协程抛出异常时,能够正确地处理这些异常。这样可以避免出现 "_GatheringFuture 异常从未检索到" 的错误。

下面是一个示例代码,演示了如何处理 asyncio.CancelledError 和 "_GatheringFuture 异常从未检索到" 异常:

Python

import asyncio

async def coroutine():

try:

while True:

awAIt asyncio.sleep(1)

except asyncio.CancelledError:

print("Coroutine cancelled")

async def mAIn():

tasks = [asyncio.ensure_future(coroutine()) for _ in range(5)]

try:

awAIt asyncio.gather(*tasks)

except Exception as e:

print(f"Exception caught: {e}")

loop = asyncio.get_event_loop()

try:

loop.run_until_complete(mAIn())

finally:

loop.close()

在上面的示例代码中,我们定义了一个协程 coroutine(),它会每隔一秒钟打印一次信息。我们创建了 5 个协程任务,并使用 asyncio.ensure_future() 函数将它们包装成 Future 对象。在 mAIn() 函数中,我们使用 asyncio.gather() 函数等待所有协程任务完成,并使用 try-except 块来捕获异常。最后,我们使用 asyncio.get_event_loop() 函数获取事件循环,并通过 loop.run_until_complete() 函数运行主协程。在程序最后,我们关闭事件循环。

通过以上的处理,我们可以有效地处理 asyncio.CancelledError 和 "_GatheringFuture 异常从未检索到" 异常,并确保我们的程序能够正常运行。这样可以提高程序的稳定性和可靠性,避免出现一些意外的问题。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号