Simple example with spawnProcess

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 remove the dictionary subprocess element from which the subprocess will exit. How to do it?

+4
source share
1 answer
 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() 

Pay attention to a couple of things:

  • You cannot call the .run () reactor for each iteration through a loop. You can only call the .run () reactor once. Fortunately, everything is needed, because as soon as it starts, it can process any number of processes.
  • transport.pid no longer valid in time when processExited is called, so if you need to use it after exiting the process, you need to save it earlier. This is what happens in the connectionMade method.
  • Removing things from a subprocess dictionary is the same as deleting anything from any dictionary.
+9
source

All Articles