Python編程:trio模塊異步/等待本地I/O庫(kù)
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 # 計(jì)時(shí)器 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 ############## 同步執(zhí)行 ###################### 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() ############## 異步執(zhí)行 ###################### 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
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
執(zhí)行結(jié)果
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
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。