Python Twisted with callInThread

I uninstalled my application, but this should give you an example of what I'm doing

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()

I have an application that I want to connect to and run an application that constantly spits out data in stdout. Now my application is working, but the problem is that the client leaves the socket connection, // usr / bin / app continues to work. The more socket connections, the more this application still works.

In any case, you can kill the run_app () function from Echo Procool?

+3
source share
2 answers

There are several suggestions that I can make, and I hope it solves your problems.

Do not use the .callFromThread reactor, use deferToThread instead

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 . , , , .

+1

Popen. . , Echo , - "getmore".

+3

Source: https://habr.com/ru/post/1772722/


All Articles