Breaking out of a while loop with a key press?
Rüdiger Mähl
ruediger.maehl at web.de
Tue Apr 1 02:40:55 EST 2003
"Richard" <richardd at hmgcc.gov.uk> wrote:
> Hi,
>
> Can anyone suggest a simple way of detecting a key press and existing
> the program? I have a program which at the moment uses a while True:
> statement. However this is not ideal as I have to close down the
> console window to exist the program. Can anyone tell me the proper way
> of doing this? So that a CTRL-C, for example, can quit the program
> correctly?
Hi Richard,
perhaps, you are looking for a simple approach like
the following sample.
HTH, Ruediger
# ========================================
import sys
import time
import atexit
import signal
CONTROL_C = False
def program_exit():
# You may do some clean-up here, but you don't have to.
print "Exiting application"
def ctrlCHandler(*whatever):
# Just sets the value of CONTROL_C
global CONTROL_C
CONTROL_C = True
print
print "Interrupt caught! Please wait..."
print
# You must check CONTROL_C in your program
# call this procedure, if control-c is pressed.
signal.signal(signal.SIGINT, ctrlCHandler)
# program_exit is called, when sys.exit is executed.
atexit.register(program_exit)
while 1:
print "Waiting for Ctrl-C to be pressed..."
time.sleep(2)
if CONTROL_C: sys.exit(0)
# ========================================
More information about the Python-list
mailing list