Python编程:trio模块异步/等待本地I/O库

简介: Python编程:trio模块异步/等待本地I/O库

github: https://github.com/python-trio/trio

文档: https://trio.readthedocs.io/en/latest/tutorial.html


An async/await-native I/O library for humans and snake people

安装

pip install trio

代码示例


# -*- coding: utf-8 -*-
import trio
import time
# 计时器
def timer(func):
    def inner(*args):
        start = time.time()
        ret = func(*args)
        end = time.time()
        print("{} time: {}".format(func.__name__, end - start))
        return ret
    return inner
############## 同步执行 ######################
def sync_add(x, y):
    time.sleep(2)
    print("sync_add: {}".format(x + y))
def sync_multiply(x, y):
    time.sleep(2)
    print("sync_multiply: {}".format(x * y))
@timer
def sync_func():
    sync_add(1, 1)
    sync_multiply(1, 1)
sync_func()
############## 异步执行 ######################
async def async_add(x, y):
    await trio.sleep(2)
    print("async_add: {}".format(x + y))
async def async_multiply(x, y):
    await trio.sleep(2)
    print("async_multiply: {}".format(x * y))
async def async_func():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(async_add, 1, 1)
        nursery.start_soon(async_multiply, 1, 1)
@timer
def run_async():
    trio.run(async_func)
run_async()

执行结果


         

相关文章
|
1天前
|
存储 人工智能 数据挖掘
Python编程入门:从基础到实战
【9月更文挑战第26天】 在这篇文章中,我们将一起探索Python编程的奇妙世界。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供有价值的信息和技巧。我们将从Python的基本语法开始,然后逐步深入到更复杂的主题,如函数、类和模块。最后,我们将通过一个实际的项目来应用我们所学的知识。让我们一起开始这段Python编程之旅吧!
|
21小时前
|
机器学习/深度学习 Python
9-3|使用Python的scikit-learn库来训练一个逻辑回归模型,检测句子是否含有侮辱性内容:
9-3|使用Python的scikit-learn库来训练一个逻辑回归模型,检测句子是否含有侮辱性内容:
|
21小时前
|
Python
7-14|salt之安装Python模块
7-14|salt之安装Python模块
|
1天前
|
Python
python编程获取续蜀山剑侠传:从目录名称、网址到内容
python编程获取续蜀山剑侠传:从目录名称、网址到内容
|
1天前
|
移动开发 Python Windows
python编程获取网页标题title的几种方法及效果对比(源代码)
python编程获取网页标题title的几种方法及效果对比(源代码)
|
1天前
|
Python
python编程获取《续蜀山剑侠传》目录信息:目录名称和网址
python编程获取《续蜀山剑侠传》目录信息:目录名称和网址
|
1天前
|
监控 网络协议 数据库连接
Python3 监控端口:使用 socket 库
Python3 监控端口:使用 socket 库
|
1天前
|
Python
告别低效!Python并查集:数据结构界的超级英雄,拯救你的编程人生!
告别低效!Python并查集:数据结构界的超级英雄,拯救你的编程人生!
5 0
|
4月前
|
人工智能 安全 Java
Python 多线程编程实战:threading 模块的最佳实践
Python 多线程编程实战:threading 模块的最佳实践
224 5
|
4月前
|
安全 调度 Python
什么是Python中的事件驱动编程?如何使用`asyncio`模块实现异步事件处理?
【2月更文挑战第4天】【2月更文挑战第9篇】什么是Python中的事件驱动编程?如何使用`asyncio`模块实现异步事件处理?
107 0