Python Twisted与Cmd模块的集成

Joh*_*nck 6 python stdin twisted tab-completion python-cmd

我喜欢Python的TwistedCmd.我想一起使用它们.

我有一些工作,但到目前为止,我还没有想出如何使标签完成工作,因为我没有看到如何在Twisted的LineReceiver中立即接收Tab键盘事件(不按Enter键).

到目前为止,这是我的代码:

#!/usr/bin/env python

from cmd import Cmd
from twisted.internet import reactor
from twisted.internet.stdio import StandardIO
from twisted.protocols.basic import LineReceiver

class CommandProcessor(Cmd):
    def do_EOF(self, line):
        return True

class LineProcessor(LineReceiver):
    from os import linesep as delimiter # makes newline work

    def __init__(self):
        self.processor = CommandProcessor()
        self.setRawMode()

    def connectionMade(self):
        self.transport.write('>>> ')

    def rawDataReceived(self, data):
        self.processor.onecmd(data)
        self.transport.write('>>> ')

StandardIO(LineProcessor())
reactor.run()
Run Code Online (Sandbox Code Playgroud)

除了标签完成,这有点起作用.我可以输入"help"之类的命令,Cmd模块将打印结果.但是我已经失去了Cmd模块的漂亮的tab-complete功能,因为Twisted一次缓冲一行.我尝试设置LineProcessor.delimiter为空字符串,无济于事.也许我需要找一些其他的Twisted而不是LineReceiver?或者也许有一种更简单的方法可以避免我必须逐个处理每个字符?

我不能单独使用Cmd,因为我想把它变成一个网络应用程序,其中一些命令将导致发送数据,并且从网络接收数据将异步发生(并显示给用户).

因此,无论我们从上面的代码开始还是完全不同的东西,我都想在Python中构建一个友好的,友好的终端应用程序,它响应网络事件和标签完成.我希望我可以使用已经存在的东西而不必自己实施太多.

Dav*_*ess 9

这种方法有两个困难:

  • Cmd.onecmd 不会做任何标签处理.
  • 即使它确实如此,您的终端也需要处于cbreak模式,以便单独按键才能将其转换为Python解释器(tty.setcbreak可以处理它).
  • 如您所知,Cmd.cmdloop不是反应堆意识,并将阻止等待输入.
  • 然而,为了获得你想要的所有酷线编辑,Cmd(实际上是readline)需要直接访问stdin和stdout.

鉴于所有这些困难,您可能希望看看让CommandProcessor在其自己的线程中运行.例如:

#!/usr/bin/env python

from cmd import Cmd
from twisted.internet import reactor

class CommandProcessor(Cmd):
    def do_EOF(self, line):
        return True

    def do_YEP(self, line):
        reactor.callFromThread(on_main_thread, "YEP")

    def do_NOPE(self, line):
        reactor.callFromThread(on_main_thread, "NOPE")

def on_main_thread(item):
    print "doing", item

def heartbeat():
    print "heartbeat"
    reactor.callLater(1.0, heartbeat)

reactor.callLater(1.0, heartbeat)
reactor.callInThread(CommandProcessor().cmdloop)
reactor.run()
Run Code Online (Sandbox Code Playgroud)