Interesting.

As Michael suggested this works, mostly:

from time import sleep

def loop():
    x = 0
    while 1:
        print "x:",x
        x += 1
        sleep(0.5)

if __name__ == "__main__":
    while 1:
        try:
            loop()
        except KeyboardInterrupt:
            print "Nope, not going to stop."


Ctrl-C is ignored.  But on Win XP, at least, Ctrl-Break still exits the
program.

On 9/22/07, Michael Langford <[EMAIL PROTECTED]> 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():
>     pass
>
> def graceful_cleanup()
>     pass
>
> if "__main__" == __name__:
>        try:
>              do_stuff()
>        except:
>              graceful_cleanup()
>
>     --Michael
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.TierOneDesign.com/
> Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com
>
> On 9/22/07, James <[EMAIL PROTECTED]> 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@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to