-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathspinner_yield.py
More file actions
executable file
·49 lines (36 loc) · 1.15 KB
/
spinner_yield.py
File metadata and controls
executable file
·49 lines (36 loc) · 1.15 KB
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
#!/usr/bin/env python3
# spinner_yield.py
# credits: Example by Luciano Ramalho inspired by
# Michele Simionato's multiprocessing example in the python-list:
# https://mail.python.org/pipermail/python-list/2009-February/538048.html
import asyncio
import itertools
@asyncio.coroutine # <1>
def spin(msg):
for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
print('\r' + status, end='', flush=True)
try:
yield from asyncio.sleep(.1) # <2>
except asyncio.CancelledError: # <3>
break
print('\r', end='')
@asyncio.coroutine # <4>
def slow_function():
# pretend waiting a long time for I/O
yield from asyncio.sleep(3) # <5>
return 42
@asyncio.coroutine # <6>
def supervisor(loop):
spinner = loop.create_task(spin('thinking!')) # <7>
print('spinner object:', spinner) # <8>
result = yield from slow_function() # <9>
spinner.cancel() # <10>
return result
def main():
loop = asyncio.get_event_loop() # <11>
result = loop.run_until_complete(supervisor(loop)) # <12>
loop.close()
print('Answer:', result)
if __name__ == '__main__':
main()