Twisted Python + spawnProcess. Getting output from a command

后端 未结 1 1960
清酒与你
清酒与你 2021-02-11 10:20

I\'m working to wrap the Minecraft server application with a Twisted Python server that has a RESTful API for getting the list of currently connected players. The Twisted app st

相关标签:
1条回答
  • 2021-02-11 10:47

    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.

    0 讨论(0)
提交回复
热议问题