Here is a possible implementation using multiprocessing , as suggested by Ricardo K.,
import multiprocessing as mpr def dangerwrap(f): """ I assume f is, or eventually calls, some external function, like cython wrapped C/C++. Also assuming that f returns an object and takes no parameters """ event = mpr.Event() q = mpr.Queue() def signalling_f(): q.put(f()) event.set() f_process = mpr.Process(target = signalling_f) f_process.start() try: event.wait() except KeyboardInterrupt: f_process.terminate() f_process.join() print "Caught in dangerwrap" return None print "Exiting normally" return q.get()
Now instead of <
X = f()
which will not respond to keyboard interruptions, causing
X = dangerwrap(f)
will stop with keyboard interruption.
source share