简体   繁体   English

python multiprocess.Pool无法处理KeyboardInterrupt对吗?

[英]python multiprocess.Pool can not process KeyboardInterrupt right?

I want to terminate my program when press Ctrl-C , code as follow: 我想按Ctrl-C时终止程序,代码如下:

#!/usr/bin/env python
# encoding: utf-8

import multiprocessing
import time
import signal
import sys

def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

def worker():
    while(True):
        time.sleep(1.1234)
        print "Working..."

if __name__ == "__main__":
    pool = multiprocessing.Pool(50, init_worker)
    try:
        for i in range(50):
            pool.apply_async(worker)

        # time.sleep(10)
        pool.close()
        pool.join()

    except KeyboardInterrupt:
        print "Caught KeyboardInterrupt, terminating workers"
        pool.terminate()
        pool.join()

but this can not work right 但这行不通

You can try this way: 您可以这样尝试:

import multiprocessing
import time
import signal


def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)


def worker():
    while(True):
        time.sleep(1.1234)
        print "Working..."


if __name__ == "__main__":
    pool = multiprocessing.Pool(10, init_worker)
    result = []
    for i in range(10):
        result.append(pool.apply_async(worker))
    try:
        while True:
            time.sleep(0.5)
            if all([r.ready() for r in result]):
                break

    except KeyboardInterrupt:
        pool.terminate()
        pool.join()

    else:
        pool.close()
        pool.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python multiprocess.Pool在stdout中按顺序显示结果 - python multiprocess.Pool show results in order in stdout 当我尝试通过multiprocess.Pool在python中加速程序时,为什么多进程比单进程慢? - Why multiple process is slower than single when I'm trying to accelerate my program by multiprocess.Pool in python? Python多进程池与进程 - Python multiprocess Pool vs Process 使用multiprocess.Pool同时运行2个瓶子应用程序 - Running 2 bottle apps at the same time using multiprocess.Pool 在一个函数中使用另一个函数不适用于multiprocess.Pool - Use another function in a function does not work with multiprocess.Pool 为什么在处理来自 multiprocess.Process 的异常时,只有自己抛出才能捕获到 KeyboardInterrupt 异常? - Why when handling exceptions from multiprocess.Process KeyboardInterrupt exception can be catched only if you throw it yourself? KeyboardInterrupt 与 Python multiprocessing.Pool - KeyboardInterrupt with Python multiprocessing.Pool 使用 multiprocess.Pool 调用一个 function 需要多个并行输入 arguments - Using multiprocess.Pool to call a function that requires many input arguments in parallel 为什么python多进程池比仅一个进程慢? - Why python multiprocess pool is slower than one process only? python 多进程:父进程无法退出 - python multiprocess: parent process can not exit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM