python 2.7 - 运行子进程并在用户时间超过最大时间时终止它

时间:2013-12-17 09:33:23

标签: python python-2.7

我正在写Python 2.7需要运行子流程并在子流程用户时间超过最大时间时终止它。
可以在this answerWhat do 'real', 'user' and 'sys' mean in the output of time(1)?中找到用户时间的定义 到目前为止,我有这个:

代码

from multiprocessing import Process
import time

def do_something():
    pass

def run_process_limited_time(max_seconds):

    # init Process
    p = Process(target=do_something, args=())

    # start process
    p.start()

    run_time = 0;
    sleep_time = 1;

    while 1:

        # sleep for sleep_time seconds
        time.sleep(sleep_time)

        # increase run time
        run_time += sleep_time

        # if process is not alive, we can break the loop
        if not p.is_alive():
            break

        # if process is still alive after max_seconds, kill it!
        # TBD - condition is not sufficient 
        elif run_time > max_seconds:
            p.terminate()
            break

def main():
    run_process_limited_time(10)

if __name__ == "__main__":
    main()

问题

条件elif run_time > max_seconds不够好。我想检查最大秒数是否不超过仅限用户时间。我不确定是否可以使用Process模块进行此操作,但我愿意接受新的想法。

2 个答案:

答案 0 :(得分:1)

这是因为您正在使用{em> 使用elif语句的if语句:

from multiprocessing import Process
import time


def do_something():
    while True:
        time.sleep(100)


def run_process_limited_time(max_seconds):

    # init Process
    p = Process(target=do_something, args=())

    # start process
    p.start()

    run_time = 0
    sleep_time = 1

    while True:
        time.sleep(sleep_time)
        run_time += sleep_time
        if not p.is_alive():
            break

        if run_time > max_seconds:
            print "Process was terminated, due to exceeding max time"
            p.terminate()
            break


def main():
    run_process_limited_time(10)

if __name__ == "__main__":
    main()

尝试以上操作,应该终止该过程。

答案 1 :(得分:1)

使用resource模块的替代方案。使用signal module可以实现处理超时。返回结果可以通过多种方式处理,其中一些方法在多处理documentation中进行了描述。

from multiprocessing import Process
import time
import resource
import signal

def do_something():
    import resource
    resource.setrlimit(resource.RLIMIT_CPU, (1,1))
    def f(signo, stackframe):
        raise Exception('stop')
    signal.signal(signal.SIGXCPU, f)
    try:
        while 1:
            print 'hello'
    except:
        print 'aborted'

def run_process_limited_time(function):

    # init Process
    p = Process(target=function, args=())

    # start process
    p.start()

    p.join(2)
    p.terminate()


if __name__ == "__main__":
    run_process_limited_time(do_something)