如何在龙卷风循环中侦听关闭的标准输入事件? [英] How to listen for event of closed stdin in a tornado loop?

查看:25
本文介绍了如何在龙卷风循环中侦听关闭的标准输入事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于处理套接字中数据的后续问题.但是,我无法捕获标准输入关闭"事件.这是我现在所拥有的:

This is a follow-up question on handling the data in the socket. However, I am unable to capture the "stdin closed" event. Here's what I have now:

import sys
import tornado

from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler

class MainHandler(RequestHandler):
    def get(self):
        self.finish("foo")
application = Application([ (r"/", MainHandler), ])

@tornado.gen.coroutine
def close_callback(*args, **kwargs):
    print args, kwargs

if __name__ == "__main__":
    application.listen(8888)

    stdin = tornado.iostream.PipeIOStream(sys.stdin.fileno())
    stdin.set_close_callback(close_callback)

    IOLoop.instance().start()

还有一个测试:

$ ./tornado_sockets.py   # expect to close stdin
<C-d>    # nothing happens

另一个测试:

$ echo expect_stdin_to_be_closed | ./tornado_sockets.py
# nothing happens

如何监听标准输入的关闭?

How can I listen for closing of stdin?

推荐答案

引用 sys.stdin 不会在 ctrl-d 上关闭:

Ctrl+D 有一个奇怪的效果.它不会关闭输入流,而只会导致 C 级 fread() 返回空结果.

Ctrl+D has a strange effect. It doesn't close the input stream, but only causes a C-level fread() to return an empty result.

所以基本上你需要用空字符串断言读取行.一些没有 PipeIOStream 的例子:

So basically you need to assert read line with empty string. Some example without PipeIOStream:

from tornado.ioloop import IOLoop
import sys

def on_stdin(fd, events):
    line = fd.readline()
    print("received: %s" % repr(line))
    if line == '':
        print('stdin ctr+d')
        sys.exit()

if __name__ == "__main__":
    IOLoop.instance().add_handler(sys.stdin, on_stdin, IOLoop.READ)
    IOLoop.instance().start()

使用PipeIOStream,使用read_until_close 非常简单.回调将在关闭或 Ctrl+D 时调用.

With PipeIOStream it is pretty straightforward using read_until_close. Callback will be called on close or on Ctrl+D.

import sys
import tornado
import tornado.iostream
from tornado.ioloop import IOLoop
from functools import partial

def read(stdin, data):
    print(data)
    # below lines are unnecessary they are only for testing purposes
    stdin.close()
    IOLoop.instance().stop()

if __name__ == "__main__":
    stdin = tornado.iostream.PipeIOStream(sys.stdin.fileno())
    stdin.read_until_close(callback=partial(read, stdin))
    IOLoop.instance().start()

这篇关于如何在龙卷风循环中侦听关闭的标准输入事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆