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

网友投稿 849 2022-05-30

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

1

代码示例

# -*- 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

执行结果

sync_add: 2 sync_multiply: 1 sync_func time: 4.00608491897583 async_multiply: 1 async_add: 2 run_async time: 2.0082740783691406

1

2

3

4

5

6

7

参考

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

Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python编程:happybase读写HBase数据库
下一篇:uni-app基础 1.2.1-引入uView
相关文章