File: async_coroutines.py

package info (click to toggle)
tqdm 4.67.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 720 kB
  • sloc: python: 5,610; makefile: 160; sh: 16
file content (36 lines) | stat: -rw-r--r-- 944 bytes parent folder | download | duplicates (2)
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
"""Asynchronous examples using `asyncio`, `async` and `await`."""
import asyncio

from tqdm.asyncio import tqdm, trange


def count(start=0, step=1):
    i = start
    while True:
        new_start = yield i
        if new_start is None:
            i += step
        else:
            i = new_start


async def main():
    N = int(1e6)
    async for row in tqdm(trange(N, desc="inner"), desc="outer"):
        if row >= N:
            break
    with tqdm(count(), desc="coroutine", total=N + 2) as pbar:
        async for row in pbar:
            if row == N:
                pbar.send(-10)
            elif row < 0:
                assert row == -9
                break
    # should be ~1sec rather than ~50s due to async scheduling
    for i in tqdm.as_completed([asyncio.sleep(0.01 * i)
                                for i in range(100, 0, -1)], desc="as_completed"):
        await i


if __name__ == "__main__":
    asyncio.run(main())