Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple example with spawnProcess

Tags:

python

twisted

I have a simple example:

subprocesses = {}

class MyPP(protocol.ProcessProtocol):
    def processExited(self, reason):
        print "processExited, status %s" % (reason.value.exitCode,)


class Test:

    def run(self):
        for i in range(0, max_processes):
            pp = MyPP()
            command = ['sleep','10']
            subprocess = reactor.spawnProcess(pp, command[0], command, {})
            subprocesses[subprocess.pid] = subprocess
            reactor.run()

Test().run()

I want to delete from dictionary subprocesses element then subprocess is exited. How to do it ?

like image 295
bdfy Avatar asked Jan 20 '23 05:01

bdfy


1 Answers

subprocesses = {}
max_processes = 3

from twisted.internet import protocol, reactor

class MyPP(protocol.ProcessProtocol):
    def connectionMade(self):
        self.pid = self.transport.pid

    def processExited(self, reason):
        print "processExited, status %s" % (reason.value.exitCode,)
        del subprocesses[self.pid]
        print 'Remaining subprocesses', subprocesses


class Test:
    def run(self):
        for i in range(0, max_processes):
            pp = MyPP()
            command = ['sleep','3']
            subprocess = reactor.spawnProcess(pp, command[0], command, {})
            subprocesses[subprocess.pid] = subprocess

Test().run()
reactor.run()

Notice a couple things:

  • You cannot call reactor.run() for every iteration through the loop. You can only call reactor.run() once. Fortunately that's all that's needed, because once it is running it can handle any number of processes.
  • The transport.pid is no longer valid by the time processExited is called, so if you need to use it after the process exits you need to save it earlier. This is what happens in the connectionMade method.
  • Deleting things from the subprocess dictionary is the same as deleting anything from any dictionary.
like image 198
Jean-Paul Calderone Avatar answered Jan 30 '23 22:01

Jean-Paul Calderone