[Tutor] Capturing ctrl-c

James jtp at nc.rr.com
Sat Sep 22 22:18:27 CEST 2007


Hi.  :)

I'm whipping up a program in Python and am having to deal with a user  
potentially hitting ctrl-c at any point in the program.  I'd like my  
Python program to wrap up cleanly when it receives this signal.

I did some Googling and read that Python throws a KeyboardInterrupt  
error.  What's the best way to run a specific "cleanup" function at  
*any* time the interrupt is received, regardless of where the program  
is in execution?

Most of the stuff I've read involves try-except blocks.  This makes  
sense to me if I want to protect a specific function or area of the  
code from being interrupted by ctrl-c, but I'm not sure what kind of  
structure my program must have to catch the exception at any point  
during execution.

Thoughts/ideas appreciated.  :)

Thanks!
.james


More information about the Tutor mailing list