分享

Python 实现异步操作

 网摘文苑 2023-05-22 发布于新疆

Python 3.5 及更高版本引入了关于异步操作的原生支持,主要包括 async 和 await 两个关键字,以及 asyncio 模块。

这种异步操作的主要思想是协程 (coroutine)。一个协程可以在某些点上暂停执行,以便其他协程可以运行。

这里有一个使用 asyncio 进行异步操作的基本示例:

import asyncioasync def my_coroutine(): await asyncio.sleep(1) # 休眠 1print('Hello')# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(my_coroutine())

在这个示例中,my_coroutine 是一个协程。它使用 await 关键字暂停自己的执行,等待 asyncio.sleep(1) 完成。在这个时候,其他协程可以执行。当 asyncio.sleep(1) 完成后,my_coroutine 继续执行,打印 'Hello'。

你也可以同时运行多个协程。这里有个例子:

import asyncioasync def print_after(wait_time, msg):    await asyncio.sleep(wait_time)    print(msg)# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(print_after(1, 'Hello'))asyncio.run(print_after(2, 'World'))

这个程序将首先打印 'Hello',然后等待一秒后打印 'World'。

你还可以使用 asyncio.gather 来并行运行多个协程

import asyncioasync def print_after(wait_time, msg): await asyncio.sleep(wait_time) print(msg)# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(asyncio.gather(print_after(1, 'Hello'), print_after(2, 'World')))

在这个示例中,print_after(1, 'Hello') 和 print_after(2, 'World') 将并行运行。由于 'Hello' 的等待时间更短,它将首先打印,然后等待一秒后打印 'World'。

注意,这只是 Python 中异步操作的基本示例。实际上,asyncio 库提供了许多高级特性,例如事件循环、任务、Futures、信号量、队列等,可以满足更复杂的异步编程需求。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多