键盘中断python的多处理池如何使用python的多处理池处理KeyboardInterrupt事件?这是一个简单的例子:from multiprocessing import Poolfrom time import sleepfrom sys import exitdef slowly_square(i):
sleep(1)
return i*idef go():
pool = Pool(8)
try:
results = pool.map(slowly_square, range(40))
except KeyboardInterrupt:
# **** THIS PART NEVER EXECUTES. ****
pool.terminate()
print "You cancelled the program!"
sys.exit(1)
print "\nFinally, here are the results: ", resultsif __name__ == "__main__":
go()当运行上面的代码时,KeyboardInterrupt当我按下时会引发上升^C,但是该过程只是挂起,我必须在外部杀死它。我希望能够随时按下^C并使所有进程正常退出。
3 回答
繁华开满天机
TA贡献1816条经验 获得超4个赞
这是一个Python bug。在等待threading.Condition.wait()中的条件时,从不发送KeyboardInterrupt。摄制:
import threading cond = threading.Condition(threading.Lock())cond.acquire()cond.wait(None)print "done"
在wait()返回之前,不会传递KeyboardInterrupt异常,并且它永远不会返回,因此中断永远不会发生。KeyboardInterrupt几乎肯定会中断条件等待。
请注意,如果指定了超时,则不会发生这种情况; cond.wait(1)将立即收到中断。因此,解决方法是指定超时。要做到这一点,请更换
results = pool.map(slowly_square, range(40))
同
results = pool.map_async(slowly_square, range(40)).get(9999999)
或类似的。
函数式编程
TA贡献1807条经验 获得超9个赞
由于某些原因,只能Exception
正常处理从基类继承的异常。作为一种解决方法,您可以重新提升您KeyboardInterrupt
的Exception
实例:
from multiprocessing import Poolimport timeclass KeyboardInterruptError(Exception): passdef f(x): try: time.sleep(x) return x except KeyboardInterrupt: raise KeyboardInterruptError()def main(): p = Pool(processes=4) try: print 'starting the pool map' print p.map(f, range(10)) p.close() print 'pool map complete' except KeyboardInterrupt: print 'got ^C while pool mapping, terminating the pool' p.terminate() print 'pool is terminated' except Exception, e: print 'got exception: %r, terminating the pool' % (e,) p.terminate() print 'pool is terminated' finally: print 'joining pool processes' p.join() print 'join complete' print 'the end'if __name__ == '__main__': main()
通常你会得到以下输出:
staring the pool map[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]pool map complete joining pool processes join complete the end
所以,如果你点击^C
,你会得到:
staring the pool map got ^C while pool mapping, terminating the pool pool is terminated joining pool processes join complete the end
添加回答
举报
0/150
提交
取消