如何手动退出无限的三重循环,如三重奏的教程echo客户程序

时间:2019-06-17 13:06:59

标签: python python-trio

除了使用Ctrl-C或使用超时之外,是否有一种方法可以手动退出三重循环无限循环,例如三重循环教程https://trio.readthedocs.io/en/latest/tutorial.html#an-echo-client中的echo客户端?

我的想法是使用从另一个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,并且想知道是否从另一个脚本调用此echo客户程序,如何精确地触发幼儿园中的cancel_scope.cancel()吗?或者,还有更好的方法?真的感谢所有帮助。谢谢。

2 个答案:

答案 0 :(得分:2)

如果您想使用键盘输入来退出,这是针对Linux和Mac OS X的解决方案。您可以使用Python msvcrt模块在​​Windows上执行类似的操作。

我从the Trio tutorial复制了echo-client.py,并在添加的三个代码块上添加了“ NEW”注释。在REPL中,您可以输入'q'取消保育范围并退出:

# -- NEW
import termios, tty

import sys
import trio

PORT = 12345
BUFSIZE = 16384

# -- NEW
async def keyboard():
    """Return an iterator of characters from stdin."""
    stashed_term = termios.tcgetattr(sys.stdin)
    try:
        tty.setcbreak(sys.stdin, termios.TCSANOW)
        while True:
            yield await trio.run_sync_in_worker_thread(
                sys.stdin.read, 1,
                cancellable=True
            )
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSANOW, stashed_term)

async def sender(client_stream):
    print("sender: started!")
    while True:
        data = b"async can sometimes be confusing, but I believe in you!"
        print("sender: sending {!r}".format(data))
        await client_stream.send_all(data)
        await trio.sleep(1)

async def receiver(client_stream):
    print("receiver: started!")
    while True:
        data = await client_stream.receive_some(BUFSIZE)
        print("receiver: got data {!r}".format(data))
        if not data:
            print("receiver: connection closed")
            sys.exit()

async def parent():
    print("parent: connecting to 127.0.0.1:{}".format(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)

            # -- NEW
            async for key in keyboard():
                if key == 'q':
                    nursery.cancel_scope.cancel()

trio.run(parent)

tty.setcbreak的调用将终端置于无缓冲模式,因此您不必在程序接收输入之前按回车键。它还可以防止字符回显到屏幕上。此外,顾名思义,它允许Ctrl-C正常工作。

finally块中,termios.tcsetattr将终端恢复到tty.setcbreak之前的模式。因此,您的终端在退出时即可恢复正常。

sys.stdin.read是在单独的线程中生成的,因为它需要以阻塞模式运行(在异步上下文中效果不佳)。原因是stdin shares its file descriptionstdoutstderr。将stdin设置为非阻塞也会将stdout设置为非阻塞,这是副作用,并且可能会导致print函数出现问题(在我的情况下为截断)。

进程间通信

这是一个使用套接字从另一个取消一个Trio进程的基本示例:

# infinite_loop.py    
import trio    

async def task():     
    while True:       
        print("ping")    
        await trio.sleep(0.5)    

async def quitter(cancel_scope):      
    async def quit(server_stream):    
        await server_stream.receive_some(1024)    
        cancel_scope.cancel()    
    await trio.serve_tcp(quit, 12346)    

async def main():    
    async with trio.open_nursery() as nursery:    
        nursery.start_soon(task)    
        nursery.start_soon(quitter, nursery.cancel_scope)    

trio.run(main)
# slayer.py        
import trio    

async def main():    
    async with await trio.open_tcp_stream("127.0.0.1", 12346) as s:
        await trio.sleep(3)    
        await s.send_all(b'quit')    

trio.run(main)

答案 1 :(得分:1)

有很多方法可以做到这一点。为什么不只使用Ctrl-C?对我来说似乎完全有效。

如果您真的不想使用Ctrl-C,那么您将需要一个函数来监听输入并更新FLAG(或者直接退出程序;我不认为老实说,您完全需要FLAG逻辑)。

例如,您可以具有一个从文件中轮询/从db中读取/侦听终端输入等的函数,并使该函数并行运行。侦听器应在同一Python脚本中作为单独的工作程序运行。但是根据您选择的方式,更改外部输入的功能可以是独立的脚本