how to stop execution on KeyboardInterrupt while using multiprocessing.Pool #python [duplicate]

主宰稳场 提交于 2020-02-04 01:26:53

问题


Possible Duplicate:
Keyboard Interrupts with python's multiprocessing Pool

Python's multiprocessing module has something called Pool http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool

While a pool of processes is operating, I can't get the script to terminate using KeyboardInterrupt i.e Ctrl + c. The pool spawns new processes and the only way to get out is ctrl + z followed by killing them manually.

Here is the script that I tried to test it on:

import multiprocessing
import random
import time

def sometask(arg):
    #do something nasty to arg
    time.sleep(arg)
    return random.randint(0,arg)

if __name__=="__main__":
    pool = multiprocessing.Pool(processes=4)
    print pool.map(sometask, range(10))

My main script tries to do something that is much more time consuming than time.sleep() and every time I try to test run it, I have to wait for it to finish or kill it manually by first finding the id of the processes it spawned. Please suggest a work around.


回答1:


I faced this problem too. A possible work around (a dirty one) can be spawn another process and pass that process the PID of the main script. Let that process kill the main script. I have tried this and it works fine for me.



来源:https://stackoverflow.com/questions/11505235/how-to-stop-execution-on-keyboardinterrupt-while-using-multiprocessing-pool-pyt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!