有没有办法手动退出三重奏无限循环,例如三重奏教程中的回声客户端,https://trio.readthedocs.io/en/latest/tutorial.html#an-echo-client,除了使用Ctrl-C
或使用超时?
我的想法是使用从另一个 python 脚本调用 echo 客户端,并且能够使用相同的 python 脚本任意关闭它。我正在考虑使用标志(也许是事件?)作为触发cancel_scope.cancel()
托儿所的开关。但我不知道如何触发开关。下面是我修改教程回显客户端代码的尝试。
import sys
import trio
PORT = 12345
BUFSIZE = 16384
FLAG = 1 # FLAG is a global variable
async def sender(client_stream):
print("sender: started")
while FLAG:
data = b'async can sometimes be confusing but I believe in you!'
print(f"sender: sending {data}")
await client_stream.send_all(data)
await trio.sleep(1)
async def receiver(client_stream):
print("recevier: started!")
while FLAG:
data = await client_stream.receive_some(BUFSIZE)
print(f"receiver: got data {data}")
if not data:
print("receiver: connection closed")
sys.exit()
async def checkflag(nursery): # function to trigger cancel()
global FLAG
if not FLAG:
nursery.cancel_scope.cancel()
else:
# keep this task running if not triggered, but how to trigger it,
# without Ctrl-C or timeout?
await trio.sleep(1)
async def parent():
print(f"parent: connecting to 127.0.0.1:{PORT}")
client_stream = await trio.open_tcp_stream("127.0.0.1", PORT)
async with client_stream:
async with trio.open_nursery() as nursery:
print("parent: spawning sender ...")
nursery.start_soon(sender, client_stream)
print("parent: spawning receiver ...")
nursery.start_soon(receiver, client_stream)
print("parent: spawning checkflag...")
nursery.start_soon(checkflag, nursery)
print('Close nursery...')
print("Close stream...")
trio.run(parent)
我发现我无法在 python REPL 之后输入任何命令trio.run()
来手动更改,并且想知道我是否从另一个脚本调用此 echo 客户端,如何在托儿所中FLAG
准确触发?cancel_scope.cancel()
或者,还有更好的方法?非常感谢所有帮助。谢谢。