Interrupting Python

Rüdiger Mähl ruediger.maehl at web.de
Tue Sep 10 03:47:43 EDT 2002


"Bob Easton" <bob at eleaston.com> wrote in
news:yz5e9.4237$rU2.145619 at news4.srv.hcvlny.cv.net: 

> I have a script that can run, accessing network resources, for several
> days. Since the script does not normally need keyed input, exception
> processing 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?

Hi Bob, 

you are perhaps looking for this:

# =====
import time
import atexit
import signal

CONTROL_C = False

def program_exit():
    # clean up before exiting if necessary
    print "Exiting application"

def ctrlCHandler(*whatever):
    global CONTROL_C
    CONTROL_C = True
    print
    print "Interrupt caught! Please wait..."
    print
    # You must check CONTROL_C in your program

signal.signal(signal.SIGINT, ctrlCHandler)

# optionally, if you need clean up actions
atexit.register(program_exit)

# do your task
while 1:
    print "Waiting for Control-C"
    time.sleep(2)
    if CONTROL_C: break
    
print "Finished"    
# =====

HTH, 

Rüdiger



More information about the Python-list mailing list