keyboard command to break out of infinite loop?

Scott David Daniels scott.daniels at acm.org
Sun Apr 16 14:02:17 EDT 2006


zweistein wrote:
> Try CTRL + C. If it doesn't work, CTRL + Pause/Break should also work
> (if you're running it from the CLI).
> 
> HTH
> 
Note: this will raise a KeyboardInterrupt exception, which you might
inadvertently be catching.  If you have been lazy and written:
     try:
         <watched code>
     except:
         <some code>
You may get to <some code> if the Control-C (or Control-Break) is
processed in the <watched code> section.  This is one reason we always
urge people to be specific about the exceptions they expect.  The
following code demonstrates what is happening:

     try:
         response = raw_input('Prompt: ')
     except:
         print 'Got here'

If you run this code and hit Control-C in response to the prompt
(guaranteeing you are inside the try-except block), you will see
a "Got here" printed.  Similarly, you can look for this one exception,
and treat it specially:

     try:
         response = raw_input('Prompt: ')
     except KeyboardInterrupt, error:
         print 'Got here with "%s" (%r)' % (error, error)

Running this and entering Control-C at the prompt will show you
that the exception you get from a KeyboardInterrupt has a reasonable
repr (the result of the %r translation), but its str conversion (the
result of the %s translation) is a zero length string (which is kind
of hard to see in a print).

So, avoid "except:" when catching exceptions, and your life will be
happier.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list