X Tutup
Skip to content

Commit 12d1bb3

Browse files
committed
revised spinner
1 parent 28d6d03 commit 12d1bb3

File tree

4 files changed

+56
-1
lines changed

4 files changed

+56
-1
lines changed

17-it-generator/sentence_gen2.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ def __iter__(self):
2222
yield match.group() # <3>
2323

2424
# end::SENTENCE_GEN2[]
25+

19-concurrency/spinner_async.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# tag::SPINNER_ASYNC_TOP[]
88
import asyncio
99
import itertools
10+
import time
1011

1112
async def spin(msg: str) -> None: # <1>
1213
for char in itertools.cycle(r'\|/-'):

19-concurrency/spinner_async_experiment.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,15 @@ async def spin(msg: str) -> None:
2020

2121
# tag::SPINNER_ASYNC_EXPERIMENT[]
2222
async def slow() -> int:
23+
print("start waiting")
2324
time.sleep(3) # <4>
2425
return 42
2526

2627
async def supervisor() -> int:
2728
spinner = asyncio.create_task(spin('thinking!')) # <1>
2829
print(f'spinner object: {spinner}') # <2>
29-
result = await slow() # <3>
30+
result = await slow() # <3>\
31+
print("End waiting")
3032
spinner.cancel() # <5>
3133
return result
3234
# end::SPINNER_ASYNC_EXPERIMENT[]
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# spinner_async.py
2+
3+
# credits: Example by Luciano Ramalho inspired by
4+
# Michele Simionato's multiprocessing example in the python-list:
5+
# https://mail.python.org/pipermail/python-list/2009-February/675659.html
6+
7+
# tag::SPINNER_ASYNC_TOP[]
8+
import asyncio
9+
import itertools
10+
import time
11+
12+
13+
async def spin(msg: str) -> None: # <1>
14+
print("start spinning")
15+
for char in itertools.cycle(r'\|/-'):
16+
status = f'{char} {msg}'
17+
print(status)
18+
try:
19+
await asyncio.sleep(0.5) # <2>
20+
except asyncio.CancelledError: # <3>
21+
print("spinner will be broken ...")
22+
break
23+
blanks = ' ' * len(status)
24+
print(f'\r{blanks}\r', end='')
25+
async def slow() -> int:
26+
print("start slow process")
27+
await asyncio.sleep(3) # <4>
28+
return 42
29+
# end::SPINNER_ASYNC_TOP[]
30+
31+
# tag::SPINNER_ASYNC_START[]
32+
def main() -> None: # <1>
33+
result = asyncio.run(supervisor()) # <2>
34+
print(f'Answer: {result}')
35+
36+
async def supervisor() -> int: # <3>
37+
spinner = asyncio.create_task(spin('thinking!')) # <4>
38+
print(f'spinner object: {spinner}') # <5>
39+
result = await slow() # <6>
40+
41+
print("0.8 wait starts")
42+
await asyncio.sleep(0.8)
43+
print("0.8 wait ends")
44+
print("start cancel spinning")
45+
spinner.cancel() # <7>
46+
47+
return result
48+
49+
if __name__ == '__main__':
50+
main()
51+
# end::SPINNER_ASYNC_START[]

0 commit comments

Comments
 (0)
X Tutup