2010-11-02 137 views
3

我剥了下来我的应用程序,但是这应该给你的我做Python的扭曲与callInThread

def run_app(f): 
    p = Popen(['/usr/bin/app'],stdout=PIPE) 
    while True: 
     o = p.stdout.readline() 
     if o == '' and p.poll() != None: break 

     reactor.callFromThread(f, o) 

class Echo(Protocol): 
    def connectionMade(self): 

     reactor.callInThread(run_app, self.appDataReceived) 

    def dataReceived(self, data): 
     data = data.strip() 
     if data == "getmore": 
      print "getmore" 

    def appDataReceived(self, u): 
     print u 

def main(): 
    factory = Factory() 
    factory.protocol = Echo 
    reactor.listenTCP(3646, factory) 
    reactor.run() 

if __name__ == "__main__": 
    main() 

我有什么,我想在连接和运行一个应用程序,不断地吐出了一个应用程序的例子数据到标准输出。现在我的应用程序可以工作,但问题是当客户端退出套接字连接时,/ usr/bin/app仍然继续运行。更多的套接字连接使得这个应用程序仍在运行。

无论如何Echo Procool杀死run_app()函数?

+0

你可以检查是否满足条件:if o ==''and p.poll()!= None:break – pyfunc 2010-11-02 21:03:44

回答

1

有几个建议,我可以做,并希望它可以解决您的问题。

不要使用reactor.callFromThread,而是使用deferToThread

from twisted.internet.threads import deferToThread 
deferredObj = threads.deferToThread(run_app, self.appDataReceived) 

就像你启动线程的连接时。您需要在连接丢失时采取行动。

示例代码:

class Echo(Protocol): 
    def connectionLost(self, reason): 
     print reason 
     # which is crude, there should be a more elegant answer 
     reactor.stop() 

一致认为deferToThread为短期运行任务进行了优化。实际上,最好重新执行代码,以便可以调用线程来运行进程并返回结果。