File tree Expand file tree Collapse file tree 2 files changed +50
-1
lines changed
Expand file tree Collapse file tree 2 files changed +50
-1
lines changed Original file line number Diff line number Diff line change 1- Sample code for Chapter 18 - "Concurrency with asyncio"
1+ Refactored sample code for Chapter 18 - "Concurrency with asyncio"
22
33From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
44http://shop.oreilly.com/product/0636920032519.do
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+
3+ # spinner_curio.py
4+
5+ # credits: Example by Luciano Ramalho inspired by
6+ # Michele Simionato's multiprocessing example in the python-list:
7+ # https://mail.python.org/pipermail/python-list/2009-February/538048.html
8+
9+ import curio
10+
11+ import itertools
12+ import sys
13+
14+
15+ async def spin (msg ): # <1>
16+ write , flush = sys .stdout .write , sys .stdout .flush
17+ for char in itertools .cycle ('|/-\\ ' ):
18+ status = char + ' ' + msg
19+ write (status )
20+ flush ()
21+ write ('\x08 ' * len (status ))
22+ try :
23+ await curio .sleep (.1 ) # <2>
24+ except curio .CancelledError : # <3>
25+ break
26+ write (' ' * len (status ) + '\x08 ' * len (status ))
27+
28+
29+ async def slow_function (): # <4>
30+ # pretend waiting a long time for I/O
31+ await curio .sleep (3 ) # <5>
32+ return 42
33+
34+
35+ async def supervisor (): # <6>
36+ spinner = await curio .spawn (spin ('thinking!' )) # <7>
37+ print ('spinner object:\n ' , repr (spinner )) # <8>
38+ result = await slow_function () # <9>
39+ await spinner .cancel () # <10>
40+ return result
41+
42+
43+ def main ():
44+ result = curio .run (supervisor ) # <12>
45+ print ('Answer:' , result )
46+
47+
48+ if __name__ == '__main__' :
49+ main ()
You can’t perform that action at this time.
0 commit comments