def catch_keyboard_interrupt(gen, logger=None):
    """ A generator that stops on a KeyboardInterrupt """
    running = True
    gen = iter(gen)
    while running:
        try:
            yield next(gen)
        except KeyboardInterrupt:
            if logger is not None:
                logger.warn('KeyboardInterrupt')
            running = False
        except StopIteration:
            running = False
        else:
            pass
