Twisted Python: Cannot write to a running spawned process

前端 未结 2 2071
既然无缘
既然无缘 2021-01-23 12:02

My question is, after spawning a process, the child process is looping to get data from its stdin. I would like to write new data to it using either Echo.Process.pipes[0].write(

2条回答
  •  遥遥无期
    2021-01-23 12:20

    To create a new process on each incoming connection and to redirect all input data to the process' stdin:

    #!/usr/bin/python
    from twisted.internet import reactor
    
    from twisted.internet import protocol
    
    class Echo(protocol.Protocol):
        def connectionMade(self):
            self.pp = MyPP()
            reactor.spawnProcess(self.pp, 'cat', ['cat'])
        def dataReceived(self, data):
            self.pp.transport.write(data)
        def connectionLost(self, reason):
            self.pp.transport.loseConnection()
    
    class MyPP(protocol.ProcessProtocol):
        def connectionMade(self):
            print "connectionMade!"
        def outReceived(self, data):
            print "out", data,
        def errReceived(self, data):
            print "error", data,
        def processExited(self, reason):
            print "processExited"
        def processEnded(self, reason):
            print "processEnded"
            print "quitting"
    
    factory = protocol.Factory()
    factory.protocol = Echo
    reactor.listenTCP(8200, factory)
    reactor.run()
    

提交回复
热议问题