键盘中断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
并使所有进程正常退出。
繁华开满天机
函数式编程
相关分类