How to kill a python child process created with subprocess.check_output() when the parent dies?

后端 未结 5 1835
再見小時候
再見小時候 2020-11-27 05:17

I am running on a linux machine a python script which creates a child process using subprocess.check_output() as it follows:

subprocess.check_output([\"ls\",         


        
5条回答
  •  星月不相逢
    2020-11-27 06:16

    As of Python 3.2 there is a ridiculously simple way to do this:

    from subprocess import Popen
    
    with Popen(["sleep", "60"]) as process:
        print(f"Just launched server with PID {process.pid}")
    

    I think this will be best for most use cases because it's simple and portable, and it avoids any dependence on global state.

    If this solution isn't powerful enough, then I would recommend checking out the other answers and discussion on this question or on Python: how to kill child process(es) when parent dies?, as there are a lot of neat ways to approach the problem that provide different trade-offs around portability, resilience, and simplicity.

提交回复
热议问题