Interrupting Python

Bengt Richter bokr at
Fri Sep 6 16:30:38 EDT 2002

On Fri, 6 Sep 2002 13:26:27 -0400, "Bob Easton" <bob at> wrote:

>I have a script that can run, accessing network resources, for several days.
>Since the script does not normally need keyed input, exception processing
started by crond or such?
>does not raise the keyboard exception until after the program ends normally.
>I would like to be able to interrupt if from the keyboard, but have not
>learned the trick.  How can I do this?
Doesn't this work on your system? Or is all the time spent outside the python
interpreter where the SIGINT signal might go elsewhere? Will Ctrl-Break do anything?
Look into the signal module for ways to write your own handlers etc.
man kill if you're on unix.

[13:25] C:\pywk\pi>type
def foo(n):
   global i,x
   for i in xrange(n):
       x = i**100

if __name__ == '__main__':
    import sys
        foo(int(sys.argv[1]))  # call your thing here instead
    except KeyboardInterrupt:
        print 'Interrupted by Ctrl-C'
        print 'Exited w/o interrupt'
    print 'FHOI, the last i**100 x value: %s**100 = %s' % (i, x)

[13:32] C:\pywk\pi> 1000
Exited w/o interrupt
FHOI, the last i**100 x value: 999**100 = 904792147113709042032214606239950347800488416333

--- here I hit Ctrl-C pretty quickly after starting the program:

[13:32] C:\pywk\pi> 1000
Interrupted by Ctrl-C
FHOI, the last i**100 x value: 214**100 = 688589417268581026354513628323939985152292357234

Bengt Richter

More information about the Python-list mailing list