[Tutor] Capturing ctrl-c
jason.massey at gmail.com
Mon Sep 24 14:11:48 CEST 2007
As Michael suggested this works, mostly:
from time import sleep
x = 0
x += 1
if __name__ == "__main__":
print "Nope, not going to stop."
Ctrl-C is ignored. But on Win XP, at least, Ctrl-Break still exits the
On 9/22/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
> When I do real applications with exception based languages, I almost
> always wrap the main function with a try/except block to allow me to
> gracefully shut down.
> In the case of python, this means 1> Use the main method 2> wrap its
> execution in a try catch:
> import mymodule
> def do_stuff():
> def graceful_cleanup()
> if "__main__" == __name__:
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.TierOneDesign.com/
> Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com
> On 9/22/07, James <jtp at nc.rr.com> wrote:
> > 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
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> Tutor maillist - Tutor at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor