您当前的位置: 首页 >  彭世瑜 Python

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

彭世瑜 发布时间:2019-04-03 13:04:55 ,浏览量:2

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()

执行结果

sync_add: 2
sync_multiply: 1
sync_func time: 4.00608491897583

async_multiply: 1
async_add: 2
run_async time: 2.0082740783691406

参考 异步爬虫写起来太麻烦?来试试 Trio 吧!

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0566s