Catching KeyboardInterrupt when working with PyGame
- by Sebastian P.
I have written a small Python application where I use PyGame for displaying some simple graphics.
I have a somewhat simple PyGame loop going in the base of my application, like so:
stopEvent = Event()
# Just imagine that this eventually sets the stopEvent
# as soon as the program is finished with its task.
disp = SortDisplay(algorithm, stopEvent)
def update():
""" Update loop; updates the screen every few seconds. """
while True:
stopEvent.wait(options.delay)
disp.update()
if stopEvent.isSet():
break
disp.step()
t = Thread(target=update)
t.start()
while not stopEvent.isSet():
for event in pygame.event.get():
if event.type == pygame.QUIT:
stopEvent.set()
It works all fine and dandy for the normal program termination; if the PyGame window gets closed, the application closes; if the application finishes its task, the application closes.
The trouble I'm having is, if I Ctrl-C in the Python console, the application throws a KeyboardInterrupt, but keeps on running.
The question would therefore be: What have I done wrong in my update loop, and how do I rectify it so a KeyboardInterrupt causes the application to terminate?