python#如何在使用multiprocessing.Pool时停止在KeyboardInterrupt上执行 [英] how to stop execution on KeyboardInterrupt while using multiprocessing.Pool #python
问题描述
可能重复:
使用python多处理池的键盘中断
Possible Duplicate:
Keyboard Interrupts with python's multiprocessing Pool
Python的多处理模块有一个称为Pool http://docs的东西. python.org/library/multiprocessing.html#module-multiprocessing.pool
Python's multiprocessing module has something called Pool http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool
虽然进程池正在运行,但是我无法使用KeyboardInterrupt(即Ctrl + c)来使脚本终止.该池产生新进程,唯一退出该进程的方法是ctrl + z,然后手动将其杀死.
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))
我的主脚本尝试执行比time.sleep()更耗时的事情,并且每次尝试运行它时,我都必须等待它完成或手动杀死它,方法是先找到它产生的过程.请提出解决方法.
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.
推荐答案
我也遇到了这个问题.可能的解决方法(肮脏的方法)可以生成另一个进程,并通过该进程来处理主脚本的PID.让该进程终止主脚本.我已经尝试过了,对我来说很好.
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.
这篇关于python#如何在使用multiprocessing.Pool时停止在KeyboardInterrupt上执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!