Python: asyncio
Python asyncio
2023-09-11 14:16:16 时间
改造老旧教程案例:
asyncio.gather
import asyncio async def b(): print(5) await asyncio.sleep(2) print(55) return 5 async def p(): print(4) await asyncio.sleep(1) print(44) return 55 async def main(): tasks = [b(), p()] res = await asyncio.gather(*tasks) print(res) asyncio.run(main())
asyncio.create_task
import asyncio async def b(): print(5) await asyncio.sleep(2) print(55) return 5 async def p(): print(4) await asyncio.sleep(1) print(44) return 55 async def main(): task1 = asyncio.create_task(b(), name = 'B') task2 = asyncio.create_task(p(), name = 'P') tasks = [task1, task2] done, pending = await asyncio.wait(tasks, timeout = None, return_when = asyncio.ALL_COMPLETED) print(type(done)) for task in done: print(task) print(task.result()) print(pending) print(tasks) asyncio.run(main())
new API:
import asyncio, random, datetime async def wait_and_echo(content): wait = random.randint(1, 5) print(f'print {content} after {wait} seconds') await asyncio.sleep(wait) print(f'{content} printed at {datetime.datetime.now().strftime("%H:%M:%S")}') async def main(): await asyncio.gather(*[wait_and_echo(x) for x in range(10)]) asyncio.run(main())
Step by Step:
import asyncio from datetime import datetime async def say_after(delay, content): await asyncio.sleep(delay) print(content) async def main(): print(f'started at {datetime.now().strftime("%T")}') await say_after(1, 'first') await say_after(2, 'second') print(f'finished at {datetime.now().strftime("%T")}') asyncio.run(main())
Use asyncio.create_task()
import asyncio from datetime import datetime async def say_after(delay, content): await asyncio.sleep(delay) print(content) async def main(): # asyncio.create_task() function to run coroutines concurrently as asyncio Tasks task1 = asyncio.create_task(say_after(1, 'first')) task2 = asyncio.create_task(say_after(2, 'second')) print(f'started at {datetime.now().strftime("%T")}') await task1 await task2 print(f'finished at {datetime.now().strftime("%T")}') asyncio.run(main())
Awaitables
We say that an object is an awaitable object if it can be used in an await
expression. Many asyncio APIs are designed to accept awaitables.
There are three main types of awaitable objects: coroutines, Tasks, and Futures.
import asyncio async def factorial(name, number): f = 1 for i in range(2, number + 1): print(f'Task {name}: Compute factorial({number}), currently i={i}') await asyncio.sleep(1) f *= i print(f'Task {name}: factorial({number}) = {f}') return f async def main(): # Schedule three calls *concurrently* res = await asyncio.gather(*[ factorial('A', 2), factorial('B', 3), factorial('C', 4) ]) print(res) asyncio.run(main())
Task:
import asyncio async def main(): loop = asyncio.get_running_loop() # asyncio.ProactorEventLoop # <ProactorEventLoop running=True closed=False debug=False> <class 'asyncio.windows_events.ProactorEventLoop'> print(loop, type(loop)) future = loop.create_future() # asyncio.Future print(future) await future asyncio.run(main())
import asyncio async def main(): # 获取当前事件循环 loop = asyncio.get_running_loop() # asyncio.ProactorEventLoop # <ProactorEventLoop running=True closed=False debug=False> <class 'asyncio.windows_events.ProactorEventLoop'> print(loop, type(loop)) future = loop.create_future() # asyncio.Future await loop.create_task(set_result(future)) data = await future print(data) async def set_result(future: asyncio.Future): await asyncio.sleep(2) future.set_result(55) print(future.result()) asyncio.run(main())
相关文章
- How to run python interactive in current file's directory in Visual Studio Code? Python路径问题
- python如何获取一个视频的帧率_python-使用OpenCV计算视频文件中的帧数?
- Python学习笔记_Python对象
- Python图像处理(14):神经网络分类器
- 【华为OD机试真题 python】通信误码【2022 Q4 | 100分】
- 零基础教你快速入门Python怎么学python入门?python新手学习路线
- Python初学者如何系统的学习python————Python入门学习指南--内附学习路径
- python中静态方法staticmethod用法详解
- 《python 与数据挖掘 》一 第2章 Python基础入门
- 《精通Python网络爬虫:核心技术、框架与项目实战》——3.4 网页分析算法
- 使用 Python 和 Asyncio 编写在线多人游戏(一)
- python面向对象——封装,继承,多态
- 时间差,时间戳和时间格式化python
- Python 相对路径和绝对路径--python实战(九)
- python学习之OpenCV-Python模块的部分应用示例(生成素描图和动漫图)
- python Python程序的架构
- (转)Python- sklearn之最小二乘法
- 《Python语言程序设计》——1.6 开始学习Python
- openAI的仿真环境Gym Retro的Python API接口
- 人生苦短,我用python(目录)
- Python django写视图函数request的方法和属性没有自动补全代码提示(包括写其他代码的时候函数参数的变量没有代码提示)
- Python判断一个字符串中是否存在多个子串中的一个
- Python数据类型转换
- 【ESP32Cam项目1】:ESP32Cam人脸检测(ArduinoESP32底层、Python版opencv)
- 【python 学习】——pycharm终端解释器和Python解释器配置