How to terminate a python subprocess launched with shell=True

前端 未结 12 2738
轮回少年
轮回少年 2020-11-21 04:53

I\'m launching a subprocess with the following command:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

However, when I try t

12条回答
  •  情话喂你
    2020-11-21 05:18

    None of this answers worked for me so Im leaving the code that did work. In my case even after killing the process with .kill() and getting a .poll() return code the process didn't terminate.

    Following the subprocess.Popen documentation:

    "...in order to cleanup properly a well-behaved application should kill the child process and finish communication..."

    proc = subprocess.Popen(...)
    try:
        outs, errs = proc.communicate(timeout=15)
    except TimeoutExpired:
        proc.kill()
        outs, errs = proc.communicate()
    

    In my case I was missing the proc.communicate() after calling proc.kill(). This cleans the process stdin, stdout ... and does terminate the process.

提交回复
热议问题