Ensuring subprocesses are dead on exiting Python program

后端 未结 14 1663
有刺的猬
有刺的猬 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:53

    On *nix's, maybe using process groups can help you out - you can catch subprocesses spawned by your subprocesses as well.

    if __name__ == "__main__":
      os.setpgrp() # create new process group, become its leader
      try:
        # some code
      finally:
        os.killpg(0, signal.SIGKILL) # kill all processes in my group
    

    Another consideration is to escalate the signals: from SIGTERM (default signal for kill) to SIGKILL (a.k.a kill -9). Wait a short while between the signals to give the process a chance to exit cleanly before you kill -9 it.

    0 讨论(0)
  • 2020-12-02 09:54

    poll( )

    Check if child process has terminated. Returns returncode attribute.

    0 讨论(0)
提交回复
热议问题