Is there a simple way to exit a while loop on keystroke?

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Fri Aug 31 19:33:32 EDT 2007


In message <1188578827.809840.90100 at r29g2000hsg.googlegroups.com>, gsxg
wrote:

> I am new to python, and have written a simple program to read a port
> via telnet.  I would like it to run until any key is pressed.

Did you mean "telnet" or did you mean "local terminal"? For a local
terminal, the following demo script should give you a starting point:

#!/usr/bin/python

import sys
import select
import termios
import tty

timeout = 0.0 # nonzero to wait that long for keypress

save_attrs = termios.tcgetattr(sys.stdin.fileno())
  # save terminal settings for restoration--note that this script
  # doesn't currently trap CTRL/C, so settings will not be properly
  # restored if that is hit
tty.setcbreak(sys.stdin.fileno())
  # or can use setraw to block CTRL/C
while True :
    (input_ready, _, _) = select.select((sys.stdin,), (), (), timeout)
    if sys.stdin in input_ready :
        break
    #end if
    sys.stdout.write("Running...\n")
#end while
termios.tcsetattr(sys.stdin.fileno(), termios.TCSAFLUSH, save_attrs)
sys.stdout.write("Finished.\n")




More information about the Python-list mailing list