-
-
Notifications
You must be signed in to change notification settings - Fork 394
Closed
Description
TODO: maybe a brief discussion of :exc:
KeyboardInterrupthandling?
What's the Right Way to catch KeyboardInterrupt? Here's trio's channel example:
from random import randint
import trio
async def main():
async with trio.open_nursery() as nursery:
send_channel, receive_channel = trio.open_memory_channel(0)
async with send_channel, receive_channel:
nursery.start_soon(producer, "producer", send_channel.clone())
nursery.start_soon(consumer, "consumer", receive_channel.clone())
async def producer(name, send_channel):
async with send_channel:
for i in range(30):
await trio.sleep(randint(1, 2))
await send_channel.send(f"{i} from {name}")
async def consumer(name, receive_channel):
async with receive_channel:
async for value in receive_channel:
print(f"consumer {name} got {value=}")
await trio.sleep(randint(3, 4))
trio.run(main)
Here's what happens when a ctrl-c occurs:
consumer consumer got value='0 from producer'
consumer consumer got value='1 from producer'
consumer consumer got value='2 from producer'
^CTraceback (most recent call last):
File "foo.py", line 28, in <module>
trio.run(main)
File "[...]/lib/python3.8/site-packages/trio/_core/_run.py", line 1896, in run
raise runner.main_task_outcome.error
File "foo.py", line 11, in main
nursery.start_soon(consumer, "consumer", receive_channel.clone())
File "[...]/lib/python3.8/site-packages/trio/_core/_run.py", line 741, in __aexit__
raise combined_error_from_nursery
File "[...]lib/python3.8/site-packages/trio/_core/_run.py", line 1107, in raise_cancel
raise KeyboardInterrupt
KeyboardInterrupt
sys:1: ResourceWarning: unclosed <socket.socket fd=4, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0>
sys:1: ResourceWarning: unclosed <socket.socket fd=5, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0>
I've tried various try/except changes, none of which seem to properly close the socket.
Also, why does not cloning (.clone()) both channels cause an immediate raise trio.ClosedResourceError?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels