Twisted Python:如何创建一个等待来自子进程的数据的延迟对象?

时间:2012-06-11 22:05:31

标签: python twisted deferred

在Echo协议的方法lineReceived中,我想每次写入child时生成一个延迟对象。它将等待结果,然后在子进程处理完数据后打印结果。我需要找到一种方法来做到这一点。现在,MyPP的函数outReceived从子进程中获得结果。

谢谢

from sys import executable
from os import environ
import os
from twisted.internet import reactor, defer
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet import protocol
from twisted.protocols.basic import LineReceiver
import sys
import time
import math

implementation = """
from filter import censor
censor()
"""                         

class Echo(LineReceiver): 

    def lineReceived(self, data): 
        if self.factory.pp == None:
            pp = MyPP()
            self.factory.pp = reactor.spawnProcess(pp, executable, [executable, "-c", implementation], 
                                                                   env=environ, childFDs = {0:"w", 1:"r", 2:"r"})   
        self.factory.pp.writeToChild(0, data+'\r\n')




class EchoFactory(Factory): 

    protocol = Echo 
    pp = None


class MyPP(protocol.ProcessProtocol): 

    def connectionMade(self):  
        print "connectionMade!" 

    def outReceived(self, data): 
        pass




reactor.listenTCP(11111, EchoFactory()) 
print 'in parent', os.getpid() 
reactor.run()

1 个答案:

答案 0 :(得分:1)

您需要在childDataReceived(childFD, data)实施中实施ProcessProtocol。当数据从子进程到达时,将回调它。请参阅the API docs