Breaking out of a while loop with a key press?

Robin Munn rmunn at pobox.com
Mon Mar 31 13:08:16 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?

You could use a "try: ... except KeyboardInterrupt: ..." block to detect
Ctrl-C. Although KeyboardInterrupt *should* by default not be caught, so
a Ctrl-C *should* be able to shut down your program. Are you by any
chance using a bare "try: ... except: ..." block somewhere? Don't do
that. Bare "except:" without specifying which exceptions you want to
catch is a surefire way of catching way too much, including things like
KeyboardInterrupt which you really want to allow to pass through
uncaught.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list