Ensuring subprocesses are dead on exiting Python program

后端 未结 14 1711
有刺的猬
有刺的猬 2020-12-02 09:17

Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().

If not, should

14条回答
  •  旧巷少年郎
    2020-12-02 09:29

    orip's answer is helpful but has the downside that it kills your process and returns an error code your parent. I avoided that like this:

    class CleanChildProcesses:
      def __enter__(self):
        os.setpgrp() # create new process group, become its leader
      def __exit__(self, type, value, traceback):
        try:
          os.killpg(0, signal.SIGINT) # kill all processes in my group
        except KeyboardInterrupt:
          # SIGINT is delievered to this process as well as the child processes.
          # Ignore it so that the existing exception, if any, is returned. This
          # leaves us with a clean exit code if there was no exception.
          pass
    

    And then:

      with CleanChildProcesses():
        # Do your work here
    

    Of course you can do this with try/except/finally but you have to handle the exceptional and non-exceptional cases separately.

提交回复
热议问题