How to shutdown a trio-infinite-loop like the echo client from tutorial

Is there a way to manually exit a trio infinite loop, like the echo client in the trio tutorial, https://trio.readthedocs.io/en/latest/tutorial.html#an-echo-client , other than using Ctrl-C or using timeouts?

My idea is to use call the echo client from another python script, and be able to close it arbitrarily. I was thinking of using a flag (maybe event?) as a switch to trigger the cancel_scope.cancel() in the nursery. But I am not sure how to do it. Greatly appreciate any help, Thanks.

You don’t really need to set a flag and then have that flag trigger a call to cancel_scope.cancel() – you can cut out the middleman, and call cancel_scope.cancel() directly :-).

It looks like your SO question has gotten some more detailed responses too; I’ll cross-link so folks here can find it: