【Python】如何终止以shell=True启动的子进程shell命令

问题

通过subprocess(shell=True)创建进程,会存在如下问题:

import subprocess
import time

cmd = 'sleep 12345'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
    output, error = process.communicate(timeout=10)
    print(output)
except: 
    process.kill()

while True:
    time.sleep(1)

指令执行时:
在这里插入图片描述

触发timeout后:
在这里插入图片描述
用以上方法执行,超时后,虽然进程结束了,但是shell中正在执行的指令并没有结束,仍在运行

解决方法

在代码中添加一个kill函数,将所有子进程全部结束

import subprocess
import time

import psutil

def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()

cmd = 'sleep 12345'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
    process.wait(timeout=10)
except: 
    # process.kill()
    kill(process.pid)

while True:
    time.sleep(1)

指令执行时:
在这里插入图片描述
触发timeout后:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值