Twisted Python + spawnProcess. Getting output from a command

◇◆丶佛笑我妖孽 提交于 2019-12-03 09:09:02

First, do not call writeSomeData ever. Call write. Second, having a global protocol instance is probably a bad idea, for all the usual reasons globals are generally a bad idea.

Third, add a method to the ProcessProtocol subclass for getting the information you want. The protocol's job is knowing how to turn abstract actions, like "ask for a list of players" into byte sequences to transmit and how to turn received byte sequences back into abstract actions like "the process told me these players are connected".

class NotchianProcessProtocol(protocol.ProcessProtocol):
    ...
    def listPlayers(self):
        self.transport.write("list")
        self._waiting.append(Deferred())
        return self._waiting[-1]

    def outReceived(self, bytes):
        outbuffer = self.outbuffer + bytes
        lines, leftover = parseLines(outbuffer)
        self.outbuffer = leftover

        for line in lines:
            if line.startswith('[INFO] Connected players: '):
                self._waiting.pop(0).callback(line)

Now any of your code which has a reference to a connected NotchianProcessProtocol can call listPlayers on it and get back a Deferred which will fire with connected player information shortly afterwards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!