欢迎访问宙启技术站
智能推送

Python中的gather()函数介绍与用法

发布时间:2023-12-25 22:56:33

在Python的asyncio库中,gather()是一个非常有用的函数,它允许我们同时运行多个协程,并且等待它们全部完成。

gather()函数接受一个可迭代对象(如列表)作为参数,其中包含要并行执行的协程对象。它返回一个协程对象,可以通过await语句来等待其完成。当所有协程都完成后,gather()函数会返回一个包含所有协程返回结果的列表。

下面是gather()函数的用法示例:

import asyncio

async def coro1():
    print('Running coro1')
    await asyncio.sleep(1)
    return 'Result from coro1'

async def coro2():
    print('Running coro2')
    await asyncio.sleep(2)
    return 'Result from coro2'

async def main():
    results = await asyncio.gather(coro1(), coro2())
    print(results)

asyncio.run(main())

在这个例子中,我们定义了两个协程函数coro1()和coro2(),它们分别模拟执行一些耗时的操作,并返回结果。我们还定义了一个主函数main(),它使用gather()函数来并行执行coro1()和coro2()这两个协程函数,并等待它们全部完成。

在main()函数中,我们使用await语句等待gather()函数的结果。当两个协程函数都完成后,gather()函数会返回一个包含两个结果的列表。然后,我们将结果打印出来。

当我们运行这个程序时,输出如下:

Running coro1
Running coro2
['Result from coro1', 'Result from coro2']

从输出中可以看出,coro1()和coro2()两个协程函数是同时执行的,并且耗时不同。而main()函数在等待gather()函数的结果时,会阻塞等待,直到所有协程都完成。

除了接受多个协程对象外,gather()函数还可以接受可选的return_exceptions参数。当设置为True时,如果其中一个协程发生异常,不会立即抛出异常,而是将异常对象作为结果返回。这在某些情况下可能是有用的,因为它可以避免一个协程的异常导致其他协程无法完成。

下面是一个带有return_exceptions参数的示例:

import asyncio

async def coro1():
    print('Running coro1')
    await asyncio.sleep(1)
    raise ValueError('An error occurred in coro1')

async def coro2():
    print('Running coro2')
    await asyncio.sleep(2)
    return 'Result from coro2'

async def main():
    results = await asyncio.gather(coro1(), coro2(), return_exceptions=True)
    print(results)

asyncio.run(main())

在这个示例中,coro1()函数会故意抛出一个ValueError异常。在main()函数中,我们设置了return_exceptions参数为True,这意味着即使coro1()函数发生异常,也不会立即抛出异常,而是将异常对象作为结果返回。

输出如下:

Running coro1
Running coro2
[ValueError("An error occurred in coro1"), 'Result from coro2']

从输出中可以看出,即使coro1()函数发生异常,gather()函数仍然返回了包含该异常对象的结果列表。

总结来说,gather()函数是一个非常有用的函数,可以同时运行多个协程并等待它们全部完成。它大大简化了并行执行协程的代码,并提高了程序的性能。同时,通过设置return_exceptions参数,我们可以控制对于异常的处理方式。