spinner with async/await

This commit is contained in:
Luciano Ramalho 2015-07-13 23:05:45 -03:00
parent daa096e3d2
commit 890495dceb

View File

@ -10,8 +10,7 @@ import itertools
import sys import sys
@asyncio.coroutine # <1> async def spin(msg): # <1>
def spin(msg): # <2>
write, flush = sys.stdout.write, sys.stdout.flush write, flush = sys.stdout.write, sys.stdout.flush
for char in itertools.cycle('|/-\\'): for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg status = char + ' ' + msg
@ -19,24 +18,22 @@ def spin(msg): # <2>
flush() flush()
write('\x08' * len(status)) write('\x08' * len(status))
try: try:
yield from asyncio.sleep(.1) # <3> await asyncio.sleep(.1) # <3>
except asyncio.CancelledError: # <4> except asyncio.CancelledError: # <4>
break break
write(' ' * len(status) + '\x08' * len(status)) write(' ' * len(status) + '\x08' * len(status))
@asyncio.coroutine async def slow_function(): # <5>
def slow_function(): # <5>
# pretend waiting a long time for I/O # pretend waiting a long time for I/O
yield from asyncio.sleep(3) # <6> await asyncio.sleep(3) # <6>
return 42 return 42
@asyncio.coroutine async def supervisor(): # <7>
def supervisor(): # <7> spinner = asyncio.ensure_future(spin('thinking!')) # <8>
spinner = asyncio.async(spin('thinking!')) # <8>
print('spinner object:', spinner) # <9> print('spinner object:', spinner) # <9>
result = yield from slow_function() # <10> result = await slow_function() # <10>
spinner.cancel() # <11> spinner.cancel() # <11>
return result return result