python asyncio

python协程库asyncio的运行方式有哪些?我们一起了解一下吧!

asyncio 是以协程的模式来编写并发的库,使用 async/await 语法。在 IO密集型 的网络编程里,异步IO 协程 省去了开辟新的线程和进程的开销。asyncio 是 Python3.4 版本引入到标准库,python3.5 加入了 async/await 特性。下面我们就来分享一下运行协程的几种方式。

使用 async 声明协程

async def asyncTask():

# 协程休眠

await asyncio.sleep(1)

print(time.strftime('%X'))

运行协程的几种方式:

1、asyncio.run() 函数用来在非协程函数中调用协程

asyncio.run(asyncTask())

2、使用 await 等待一个协程。

await asyncTask()

3、asyncio.create_task() 用函数将协程打包为一个 Task 排入日程准备执行,返回 asyncio.Task 对象。

此函数 在 Python 3.7 中被加入。

task1 = asyncio.create_task(asyncTask1())task2 = asyncio.create_task(asyncTask2())await task1await task2

4、使用 asyncio.gather() 函数来并发多个协程。

tasks = asyncio.gather(asyncTask1(), asyncTask2())tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])await tasksawait tasks2

具体示例:

import asyncioimport time# 定义协程任务async def asyncTask1():

# 协程休眠

await asyncio.sleep(1)

print(time.strftime('%X'), 1)async def asyncTask2():

await asyncio.sleep(2)

print(time.strftime('%X'), 2)async def main():

task1 = asyncio.create_task(asyncTask1())

task2 = asyncio.create_task(asyncTask2())

tasks = asyncio.gather(asyncTask1(), asyncTask2())

tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()]) await tasks await tasks2 await task1 await task2

print(time.strftime('%X'), "start")

asyncio.run(main())

print(time.strftime('%X'), "end")

关于运行协程的方式,我们就了解到这啦!


标签:asyncio python

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
Python工程师要学习多久
2022-08-05
Python工程师要学习多久
python学完能干什么
2022-08-05
python学完能干什么
python中append
2022-08-05
python中append
python函数大全及使用
2022-08-05
python函数大全及使用
python语言是什么
2022-08-05
python语言是什么
python操作excel表格
2022-08-05
python操作excel表格
python语言可以干什么
2022-08-05
python语言可以干什么
Python要学些什么
2022-08-05
Python要学些什么
python都可以干什么
2022-08-05
python都可以干什么
python就业前景怎么样
2022-08-05
python就业前景怎么样
手机老是弹出广告怎么解决
2022-08-05
手机老是弹出广告怎么解决
小爱同学怎么判断我喜欢的人喜不喜欢我
2022-08-05
小爱同学怎么判断我喜欢的人喜不喜欢我
安卓手机如何打开.kmz文件
2022-08-05
安卓手机如何打开.kmz文件
苹果手机文件管理在哪里
2022-08-05
苹果手机文件管理在哪里
安卓手机如何打开.sav文件
2022-08-05
安卓手机如何打开.sav文件
结婚32年是什么婚
2022-07-28
结婚32年是什么婚
怎么晒苦瓜干不变色
2022-07-28
怎么晒苦瓜干不变色
相互配合的经典语录
2022-07-28
相互配合的经典语录
苹果锁屏延迟一秒怎么回事
2022-07-28
苹果锁屏延迟一秒怎么回事
红米note10与红米note10pro区别
2022-07-28
红米note10与红米note10pro区别
快手有赞地址在哪修改
2022-07-28
快手有赞地址在哪修改
放心购是什么购物平台
2022-07-28
放心购是什么购物平台
淘宝两个钻石是什么等级
2022-07-28
淘宝两个钻石是什么等级
微信一定要实名认证才能用吗
2022-07-28
微信一定要实名认证才能用吗
微博炸号是啥意思
2022-07-28
微博炸号是啥意思