11#!/usr/bin/env python 
22""" 
3- (Python >= 3.5 ) 
3+ (Python >= 3.6 ) 
44This is an example of how to prompt inside an application that uses the asyncio 
55eventloop. The ``prompt_toolkit`` library will make sure that when other 
66coroutines are writing to stdout, they write above the prompt, not destroying 
1919from  prompt_toolkit .patch_stdout  import  patch_stdout 
2020from  prompt_toolkit .shortcuts  import  PromptSession 
2121
22- loop  =  asyncio .get_event_loop ()
2322
2423
2524async  def  print_counter ():
2625 """ 
2726 Coroutine that prints counters. 
2827 """ 
29-  i  =  0 
30-  while  True :
31-  print ('Counter: %i'  %  i )
32-  i  +=  1 
33-  await  asyncio .sleep (3 )
28+  try :
29+  i  =  0 
30+  while  True :
31+  print ('Counter: %i'  %  i )
32+  i  +=  1 
33+  await  asyncio .sleep (3 )
34+  except  asyncio .CancelledError :
35+  print ('Background task cancelled.' )
3436
3537
3638async  def  interactive_shell ():
@@ -49,16 +51,20 @@ async def interactive_shell():
4951 return 
5052
5153
52- def  main ():
54+ async   def  main ():
5355 with  patch_stdout ():
54-  shell_task  =  asyncio .ensure_future (interactive_shell ())
55-  background_task  =  asyncio .gather (print_counter (), return_exceptions = True )
56- 
57-  loop .run_until_complete (shell_task )
58-  background_task .cancel ()
59-  loop .run_until_complete (background_task )
56+  background_task  =  asyncio .create_task (print_counter ())
57+  try :
58+  await  interactive_shell ()
59+  finally :
60+  background_task .cancel ()
6061 print ('Quitting event loop. Bye.' )
6162
6263
6364if  __name__  ==  '__main__' :
64-  main ()
65+  try :
66+  from  asyncio  import  run 
67+  except  ImportError :
68+  asyncio .run_until_complete (main ())
69+  else :
70+  asyncio .run (main ())
0 commit comments