通过os.system()杀死在Process中启动的脚本

L.J*_*.J. 5 python os.system process

我有一个python脚本,它启动了几个进程.每个进程基本上只调用一个shell脚本:

from multiprocessing import Process
import os
import logging

def thread_method(n = 4):
    global logger
    command = "~/Scripts/run.sh " + str(n) + " >> /var/log/mylog.log"
    if (debug): logger.debug(command)
    os.system(command)
Run Code Online (Sandbox Code Playgroud)

我发布了几个这些线程,它们都是在后台运行的.我希望在这些线程上有一个超时,这样如果超过超时,它们就会被杀死:

t = []
for x in range(10):
    try:
        t.append(Process(target=thread_method, args=(x,) ) )
        t[-1].start()
    except Exception as e:
        logger.error("Error: unable to start thread")
        logger.error("Error message: " + str(e))
logger.info("Waiting up to 60 seconds to allow threads to finish")
t[0].join(60)
for n in range(len(t)):
    if t[n].is_alive():
    logger.info(str(n) + " is still alive after 60 seconds, forcibly terminating")
     t[n].terminate()
Run Code Online (Sandbox Code Playgroud)

问题是在进程线程上调用terminate()并不会杀死已启动的run.sh脚本 - 它会继续在后台运行,直到我从命令行强制终止它,或者它在内部完成.有没有办法终止也杀死os.system()创建的子shell?

Ign*_*ams 2

相反,使用subprocess它的对象有一个明确的terminate()方法。