问题
通过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后: