Catching KeyboardInterrupt when working with PyGame

Posted by Sebastian P. on Stack Overflow See other posts from Stack Overflow or by Sebastian P.
Published on 2010-05-12T14:51:37Z Indexed on 2010/05/12 14:54 UTC
Read the original article Hit count: 210

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about pygame