1

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

我对Twisted很陌生,但我假设我需要编写一个延迟函数,读取.stdintransport.write(sane_command)

有谁知道延迟解析命令行以获取输入的示例?

4

2 回答 2

2

这是我为后代提出的代码(基于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()
于 2013-04-11T09:49:46.540 回答