Get to know signal module
Use signal module
Defining our own signal handler
import time# from w w w. j av a 2s . c o m
import signal
def stop( signalNumber, frame ):
global keepRunning
keepRunning -= 1
print "Ctrl-C pressed; keepRunning is", keepRunning
keepRunning = 3
signal.signal( signal.SIGINT, stop )
while keepRunning:
print "Executing..."
time.sleep( 1 )
The code above generates the following result.