Breaking out of a while loop with a key press?

Robin Munn rmunn at pobox.com
Tue Apr 1 10:06:38 EST 2003


Carl Banks <imbosol-1049135446 at aerojockey.com> wrote:
> Robin Munn wrote:
>> 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.
> 
> In this case, it shouldn't.  He's running his program in a console
> window created within Python.  The idea of a console is
> (theoretically) to give a program complete control of this input;
> therefore, console windows often disable KeyboardInterrupt and treat
> Control-C like any regular keystroke.

Ah. I was assuming something like the Linux console, or the Windows
"console" that's almost-but-not-entirely like a Unix console in
behavior...

-- 
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