updated more ch. 18 examples to Python 3.7

This commit is contained in:
Luciano Ramalho
2019-01-23 20:45:59 -02:00
parent 29d6835f3b
commit 176dc38c42
4 changed files with 47 additions and 64 deletions

28
18-asyncio-py3.7/spinner_asyncio.py Normal file → Executable file
View File

@@ -1,10 +1,12 @@
# spinner_await.py
#!/usr/bin/env python3
# spinner_asyncio.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
# BEGIN SPINNER_AWAIT
# BEGIN SPINNER_ASYNCIO
import asyncio
import itertools
import sys
@@ -18,31 +20,31 @@ async def spin(msg): # <1>
flush()
write('\x08' * len(status))
try:
await asyncio.sleep(.1) # <3>
except asyncio.CancelledError: # <4>
await asyncio.sleep(.1) # <2>
except asyncio.CancelledError: # <3>
break
write(' ' * len(status) + '\x08' * len(status))
async def slow_function(): # <5>
async def slow_function(): # <4>
# pretend waiting a long time for I/O
await asyncio.sleep(3) # <6>
await asyncio.sleep(3) # <5>
return 42
async def supervisor(): # <7>
spinner = asyncio.create_task(spin('thinking!')) # <8>
print('spinner object:', spinner) # <9>
result = await slow_function() # <10>
spinner.cancel() # <11>
async def supervisor(): # <6>
spinner = asyncio.create_task(spin('thinking!')) # <7>
print('spinner object:', spinner) # <8>
result = await slow_function() # <9>
spinner.cancel() # <10>
return result
def main():
result = asyncio.run(supervisor()) # <12>
result = asyncio.run(supervisor()) # <11>
print('Answer:', result)
if __name__ == '__main__':
main()
# END SPINNER_AWAIT
# END SPINNER_ASYNCIO