如何使用 python 的多处理池来处理 KeyboardInterrupt 事件:
from multiprocessing import Pool
from time import sleep
from sys import exit
def slowly_square(i):
sleep(1)
return i*i
def 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: ", results
if __name__ == "__main__":
go()
当运行上面的代码时,当我按下 ^C
时,KeyboardInterrupt
会升高,但是进程只是挂起在那个点上,我必须在外部终止它。
我希望能够按 ^C
在任何时候,并导致所有的进程退出优雅。