Skip to content

Instantly share code, notes, and snippets.

@azami
Last active December 27, 2015 04:19
Show Gist options
  • Save azami/7266061 to your computer and use it in GitHub Desktop.
Save azami/7266061 to your computer and use it in GitHub Desktop.
使えるかどうかわからないけどCtrl+Cで停止するmultiprocessing.Pool
import multiprocessing
import functools
def ignore_keyboard_interrupt(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except KeyboardInterrupt:
pass
return wrapper
class Pool(multiprocessing.Pool):
def catch_keyboard_interrupt(f):
@functools.wraps(f)
def wrapper(func, *args, **kwargs):
try:
return f(ignore_keyboard_interrupt(func), *args, **kwargs)
except KeyboardInterrupt:
self.terminate()
self.close()
self.join()
exit(130)
return wrapper
@catch_keyboard_interrupt
def apply(self, func, args=(), kwds={}):
return super(Pool, self).apply(func, args, kwds)
@catch_keyboard_interrupt
def apply_async(self, func, args=(), kwds={}, callback=None):
return super(Pool, self).apply_async(func, args, kwds, callback)
@catch_keyboard_interrupt
def imap(self, func, iterable, chunksize=1):
return super(Pool, self).imap(func, iterable, chunksize)
@catch_keyboard_interrupt
def map(self, func, iterable, chunksize=None):
return super(Pool, self).map(func, iterable, chunksize)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment