- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson03_as_completed.py
More file actions
Latest commit
27 lines (24 loc) · 746 Bytes
/
Copy pathlesson03_as_completed.py
File metadata and controls
27 lines (24 loc) · 746 Bytes
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
# SuperFastPython.com
# example of getting coroutine results as completed
fromrandomimportrandom
importasyncio
# coroutine to execute in a new task
asyncdeftask_coro(arg):
# generate a random value between 0 and 1
value=random()
# suspend for a moment
awaitasyncio.sleep(value)
# return the result
returnarg*value
# main coroutine
asyncdefmain():
# create many coroutines
coros= [task_coro(i) foriinrange(10)]
# get results as coroutines are completed
forcoroinasyncio.as_completed(coros):
# get the result from the next task to complete
result=awaitcoro
# report the result
print(f'>got {result}')
# start the asyncio program
asyncio.run(main())