How to terminate a python subprocess launched with shell=True

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

    If you can use psutil, then this works perfectly:

    import subprocess
    
    import psutil
    
    
    def kill(proc_pid):
        process = psutil.Process(proc_pid)
        for proc in process.children(recursive=True):
            proc.kill()
        process.kill()
    
    
    proc = subprocess.Popen(["infinite_app", "param"], shell=True)
    try:
        proc.wait(timeout=3)
    except subprocess.TimeoutExpired:
        kill(proc.pid)
    

提交回复
热议问题