5

我有一个启动多个进程的 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)

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

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?

4

4 回答 4

4

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

于 2012-09-07T16:29:38.550 回答
2

在 Python 3.3 中,子进程模块支持超时:http ://docs.python.org/dev/library/subprocess.html

有关 Python 2.x 的其他解决方案,请查看此线程:Using module 'subprocess' with timeout

于 2012-09-07T16:34:24.907 回答
2

改为使用subprocess,其对象有一个明确的terminate()方法。

于 2012-09-07T15:36:56.407 回答
1

基于停止在 Python 中读取进程输出而不挂起?

import os
import time
from subprocess import Popen

def start_process(n, stdout):
    # no need for `global logger` you don't assign to it
    command = [os.path.expanduser("~/Scripts/run.sh"), str(n)]
    logger.debug(command) # no need for if(debug); set logging level instead
    return Popen(command, stdout=stdout) # run directly

# no need to use threads; Popen is asynchronous 
with open('/tmp/scripts_output.txt') as file:
    processes = [start_process(i, file) for i in range(10)]

    # wait at most timeout seconds for the processes to complete
    # you could use p.wait() and signal.alarm or threading.Timer instead
    endtime = time.time() + timeout
    while any(p.poll() is None for p in processes) and time.time() < endtime:
        time.sleep(.04)

    # terminate unfinished processes
    for p in processes:
        if p.poll() is None:
            p.terminate()
            p.wait() # blocks if `kill pid` is ignored

p.wait(timeout)如果可用,请使用。

于 2012-09-07T16:57:23.827 回答