开发者

simple example with spawnProcess

开发者 https://www.devze.com 2023-03-20 12:16 出处:网络
I have a simple example: subprocesses = {} class MyPP(protocol.ProcessProtocol): def processExited(self, reason):

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 ?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号