Python Twisted deferToThread函数未按预期工作

Python Twisted deferToThread函数未按预期工作,python,twisted,Python,Twisted,这里我的目标是创建一个简单的服务器来处理TCP消息,比如“processmystring”,它发送“mystring”,由一个相当耗时的操作(这里称为slowFunction)来处理。在这里,我通过deferToThread调用这个函数,但似乎什么也没发生:deferToThread的回调消息没有显示在任何地方(断点显示它从未被调用),函数中的打印也没有显示(断点显示它从未被调用) 我已经得到了我们公司的一些人的帮助 要点是:回调(onProcessDone和onError)应该采用一个结果参数

这里我的目标是创建一个简单的服务器来处理TCP消息,比如“processmystring”,它发送“mystring”,由一个相当耗时的操作(这里称为slowFunction)来处理。在这里,我通过deferToThread调用这个函数,但似乎什么也没发生:deferToThread的回调消息没有显示在任何地方(断点显示它从未被调用),函数中的打印也没有显示(断点显示它从未被调用)


我已经得到了我们公司的一些人的帮助

要点是:回调(onProcessDone和onError)应该采用一个结果参数,由DeferreThread调用的函数将接收self作为参数(它应该是MySimpleServer类的方法之一)

最终代码现在是:

from twisted import protocols
from twisted.protocols import basic
from twisted.internet import threads, protocol, reactor
from twisted.application import service, internet
import re
import time

def slowFunction(arg):
    print "starting process"
    time.sleep(20)
    print "processed "+arg

class MySimpleServer(basic.LineReceiver):

    PROCESS_COMMAND = "process (.*)" #re pattern
    clients = []

    def connectionMade(self):
        print "Client connected"
        MySimpleServer.clients.append(self)

    def connectionLost(self, reason):
        print "Client gone"
        MySimpleServer.clients.remove(self)

    def onProcessDone(self, result):
        self.message("Process done")

    def onError(self, result):
        self.message("Process fail with error")

    def processFunction(self, processArgument):
        slowFunction(processArgument)

    def lineReceived(self, line):
        processArgumentResult = re.search(MySimpleServer.PROCESS_COMMAND, line)
        if not processArgumentResult == None:
            processArgument = processArgumentResult.groups()[0] 
            deferred = threads.deferToThread(self.processFunction, processArgument)
            deferred.addCallback(self.onProcessDone)
            deferred.addErrback(self.onError)
            self.message("processing your request")
        else:
            print "Unknown message line: "+line

    def message(self, message):
        self.transport.write(message + '\n')

if __name__ == '__main__':
    factory = protocol.ServerFactory()
    factory.protocol = MySimpleServer
    factory.client = []

    reactor.listenTCP(8000, factory)
    reactor.run()

另一种方法是使用
staticmethod
;这是它唯一合法的用途

class MySimpleServer(basic.LineReceiver):
    processFunction = staticmethod(slowFunction)

小的不相关点:不要将相等与
None
进行比较,只需根据需要使用
is None
is not None
。好的,你能解释一下为什么吗?
class MySimpleServer(basic.LineReceiver):
    processFunction = staticmethod(slowFunction)