通过 os.system() 杀死进程中启动的脚本 [英] Killing a script launched in a Process via os.system()

查看:109
本文介绍了通过 os.system() 杀死进程中启动的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动多个进程的 python 脚本.每个进程基本上只调用一个shell脚本:

I have a python script which launches several processes. Each process basically just calls a shell script:

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)

我启动了其中几个线程,它们旨在在后台运行.我想在这些线程上设置超时,这样如果超过超时,它们就会被杀死:

I launch several of these threads, which are meant to run in the background. I want to have a timeout on these threads, such that if it exceeds the timeout, they are killed:

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()

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

The problem is that calling terminate() on the process threads isn't killing the launched run.sh script - it continues running in the background until I either force kill it from the command line, or it finishes internally. Is there a way to have terminate also kill the subshell created by os.system()?

推荐答案

您应该使用一个事件来通知工作线程终止,使用 subprocess 模块运行子进程,然后使用 终止它Popen.terminate().调用 Process.terminate() 将不允许工作人员进行清理.请参阅有关Process.terminate()的文档.

You should use an event to signal the worker to terminate, run the subprocess with subprocess module, then terminate it with Popen.terminate(). Calling Process.terminate() will not allow it worker to clean up. See the documentation for Process.terminate().

这篇关于通过 os.system() 杀死进程中启动的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆