【发布时间】:2019-06-17 13:06:59
【问题描述】:
除了使用Ctrl-C 或使用超时之外,有没有办法手动退出三重奏无限循环,例如三重奏教程中的 echo 客户端 https://trio.readthedocs.io/en/latest/tutorial.html#an-echo-client ?
我的想法是使用从另一个 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)
我发现我无法在trio.run() 之后将任何命令输入python REPL,手动更改FLAG,我想知道我是否从另一个脚本调用此回显客户端,如何准确触发@987654327 @在幼儿园?或者,还有更好的方法?非常感谢所有帮助。谢谢。
【问题讨论】:
标签: python python-trio