-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_queue_exception.py
58 lines (45 loc) · 1.15 KB
/
async_queue_exception.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
import asyncio
q = asyncio.Queue()
e = None
class MyException(Exception):
...
async def fill_queue(delay):
cnt = 1
while True:
await asyncio.sleep(delay)
q.put_nowait(cnt)
cnt += 1
async def counter():
cnt = 1
while True:
await asyncio.sleep(1)
print("counter: ", cnt)
cnt += 1
async def consume_queue():
return await q.get()
async def cancel_task(t: asyncio.Task, delay):
await asyncio.sleep(delay)
t.cancel()
async def raise_after(t: asyncio.Task, delay):
global e
await asyncio.sleep(delay)
try:
raise MyException("my exception")
except Exception as my_e:
e = my_e
t.cancel()
async def get_queue_val(raise_delay):
cq_task = asyncio.create_task(consume_queue())
asyncio.create_task(raise_after(cq_task, raise_delay))
try:
await cq_task
return cq_task.result()
except asyncio.CancelledError:
if e:
raise e
return None
async def main():
asyncio.create_task(fill_queue(5))
asyncio.create_task(counter())
print("queue result: ", await get_queue_val(4))
asyncio.run(main())