Interrupting Python

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


On Fri, 6 Sep 2002 13:26:27 -0400, "Bob Easton" <bob at eleaston.com> 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 catchctlc.py
i=x=0
def foo(n):
   global i,x
   for i in xrange(n):
       x = i**100

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

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

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

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


Regards,
Bengt Richter



More information about the Python-list mailing list