2013-04-10 61 views
1

我有一個包裝腳本,其中一個類派生自protocol.ProcessProtocol,它調用一段外部代碼。我想要的是能夠通過包裝器的命令行與所述代碼段進行交互。這個想法是,這個包裝將包裝幾段代碼,併爲它們提供一個(簡單的?)統一接口。請注意,此應用程序中不需要網絡連接。進程協議,延遲和命令行輸入

我很新的扭曲,但我假設我需要寫一個deferred函數讀取stdin,解析它的理智(這意味着什麼我的應用程序),然後叫transport.write(sane_command)

有誰知道延遲解析命令行輸入的例子嗎?

回答

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() 
+0

[ndpu](http://stackoverflow.com/users/1099876/ndpu)的[回覆](http://stackoverflow.com/a/15932008/232794)被接受爲他們的答案提供了缺少的鏈接我需要。 – Sardathrion 2013-04-11 09:51:14