How to terminate a python subprocess launched with shell=True

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

    As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

    if isinstance(command, unicode):
        cmd = command.encode('utf8')
    args = shlex.split(cmd)
    
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    

    Then p.kill() and p.terminate() should work how you expect.

提交回复
热议问题