@@ -963,6 +963,46 @@ of `uasyncio` by forcing the coro to run, and possibly terminate, when it is
963
963
still queued for execution. I haven't entirely thought through the implications
964
964
of this, but it's a thoroughly bad idea.
965
965
966
+ There is a "gotcha" illustrated by this code sample. If allowed to run to
967
+ completion it works as expected.
968
+
969
+ ``` python
970
+ import uasyncio as asyncio
971
+ async def foo ():
972
+ await asyncio.sleep(3 )
973
+ print (' About to throw exception.' )
974
+ 1 / 0
975
+
976
+ async def bar ():
977
+ try :
978
+ await foo()
979
+ except ZeroDivisionError :
980
+ print (' foo was interrupted by zero division' ) # Happens
981
+ raise # Force shutdown to run by propagating to loop.
982
+ except KeyboardInterrupt :
983
+ print (' foo was interrupted by ctrl-c' ) # NEVER HAPPENS
984
+ raise
985
+
986
+ async def shutdown ():
987
+ print (' Shutdown is running.' ) # Happens in both cases
988
+ await asyncio.sleep(1 )
989
+ print (' done' )
990
+
991
+ loop = asyncio.get_event_loop()
992
+ try :
993
+ loop.run_until_complete(bar())
994
+ except ZeroDivisionError :
995
+ loop.run_until_complete(shutdown())
996
+ except KeyboardInterrupt :
997
+ print (' Keyboard interrupt at loop level.' )
998
+ loop.run_until_complete(shutdown())
999
+ ```
1000
+
1001
+ However issuing a keyboard interrupt causes the exception to go to the event
1002
+ loop. This is because ` uasyncio.sleep ` causes execution to be transferred to
1003
+ the event loop. Consequently applications requiring cleanup code in response to
1004
+ a keyboard interrupt should trap the exception at the event loop level.
1005
+
966
1006
###### [ Contents] ( ./TUTORIAL.md#contents )
967
1007
968
1008
# 5 Device driver examples
0 commit comments