Making sure a Python script with subprocesses dies on SIGINT

前端 未结 5 902
感动是毒
感动是毒 2020-12-29 18:36

I\'ve got a command that I\'m wrapping in script and spawning from a Python script using subprocess.Popen. I\'m trying to make sure it dies if the

5条回答
  •  抹茶落季
    2020-12-29 19:21

    The subprocess is by default part of the same process group, and only one can control and receive signals from the terminal, so there are a couple of different solutions.

    Setting stdin as a PIPE (in contrast to inheriting from the parent process), this will prevent the child process from receiving signals associated to it.

    subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    

    Detaching from the parent process group, the child will no longer receive signals

    def preexec_function():
        os.setpgrp()
    
    subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec_function)
    

    Explicitly ignoring signals in the child process

    def preexec_function():
        signal.signal(signal.SIGINT, signal.SIG_IGN)
    
    subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec_function)
    

    This might however be overwritten by the child process.

提交回复
热议问题