-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasyncio_run_keyboardinterrupt.py
64 lines (52 loc) · 1.26 KB
/
asyncio_run_keyboardinterrupt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import asyncio
async def sleep(delay):
try:
await asyncio.sleep(delay)
except asyncio.CancelledError:
print("sleep Cancelled?")
raise
except KeyboardInterrupt:
print("sleep CtrlC!")
raise
async def test_sleep(n):
for i in range(n):
print(i)
try:
await sleep(1)
except asyncio.CancelledError:
print("test sleep Cancelled?")
raise
except KeyboardInterrupt:
print("test sleep CtrlC!")
raise
async def run():
t = asyncio.create_task(test_sleep(10))
try:
await t
except asyncio.CancelledError:
print("run Cancelled?")
raise
except KeyboardInterrupt:
print("run CtrlC!")
raise
print("run over")
await t
# try:
# asyncio.run(run())
# except KeyboardInterrupt:
# print("main CtrlC...")
# print("?")
loop = asyncio.get_event_loop()
task = loop.create_task(run())
try:
loop.run_until_complete(task)
except KeyboardInterrupt:
print("main CtrlC...")
task.cancel()
try:
loop.run_until_complete(task)
except KeyboardInterrupt:
print("main CtrlC again...")
except asyncio.CancelledError:
print("main Cancelled...")
print("?")