进程协议、延迟和命令行inpu

2024-05-15 02:01:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包装器脚本,它有一个从protocol.ProcessProtocol派生的类,它调用一个外部代码段。我想要的是能够通过包装器的命令行与所述代码段进行交互。我们的想法是,这个包装器将包装几段代码,并提供一个(简单?)统一的接口。请注意,在此应用程序中不需要联网。在

我对Twisted非常陌生,但我假设我需要编写一个deferred函数,读取stdin,解析它以确保其正常(无论这对我的应用程序意味着什么),然后调用transport.write(sane_command)。在

有人知道延迟解析命令行输入的例子吗?


Tags: 函数代码命令行脚本应用程序代码段stdintwisted
2条回答

这是我为后代设计的代码(基于code of Jp Calderone)。在

欢迎批评


import os
import tty
import sys
import termios

from pprint import pprint, pformat

from twisted.internet import reactor, stdio
from twisted.python import log

from twisted.conch.insults.insults import ServerProtocol
from twisted.conch.recvline import HistoricRecvLine
from twisted.conch.recvline import RecvLine

try:
    from fabulous.color import fg256
    _format_prompt = lambda x: fg256(63, x).as_utf8
except ImportError:
    _format_prompt = lambda x: x


class Fubar(HistoricRecvLine):

    def connectionLost(self, reason):
        print 'Connection lost because', pformat(reason)
        reactor.stop()

    def lineReceived(self, line):
        if line == "quit" or line == "exit" or line == "q":
            self.terminal.loseConnection()
        self.terminal.write('echo: %s' % (pformat(line)))
        self.terminal.nextLine()
        self.terminal.write(self.ps[self.pn])

    def connectionMade(self):
        """Called after a connection has been established."""
        pprint(self.ps)
        self.ps = (_format_prompt('echo> '), '...')
        RecvLine.connectionMade(self)
        self.historyLines = []
        self.historyPosition = 0
        t = self.terminal
        self.keyHandlers.update({t.UP_ARROW: self.handle_UP,
                                 t.DOWN_ARROW: self.handle_DOWN})


def runWithProtocol(klass):
    fd = sys.__stdin__.fileno()
    oldSettings = termios.tcgetattr(fd)
    tty.setraw(fd)
    try:
        p = ServerProtocol(klass)
        stdio.StandardIO(p)
        reactor.run()
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
        os.write(fd, "\r\x1bc\r")


def main(argv=None):
    log.startLogging(file('child.log', 'w'))
    runWithProtocol(Fubar)


if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题