How to terminate a python subprocess launched with shell=True

前端 未结 12 2742
轮回少年
轮回少年 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:27

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

    p.kill() ends up killing the shell process and cmd is still running.

    I found a convenient fix this by:

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

    This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed. p.pid will be the id of your cmd process then.

    p.kill() should work.

    I don't know what effect this will have on your pipe though.

提交回复
热议问题