can i make sys.stdin.read() not wait?

Michael Hudson mwh21 at cam.ac.uk
Thu Dec 7 05:02:54 EST 2000


thelocust at my-deja.com writes:

> I'm working on a program that requires me to read in input (usually one
> character) if it is input.  For example, i have a while loop that looks
> like this:
> 
> while 1:
>       x = sys.stdin.read(1)
>       if x == 'q':
>            break
>       test.handlestuff()
> 
> Well, my problem is is that it seems that read MUST have input to move
> on.  Is there any way that it just attempts to get whatever is on the
> TTY?  or maybe the last thing that was put to it?

You can use a mixture of select.select, termios.tcsetattr and os.read
to do what you want; something like this:

import termios
import TERMIOS
import os
import select,sys

def read1():
    oldattr = termios.tcgetattr(0)
    try:
        attr = termios.tcgetattr(0)
        attr[2] = (attr[2] & ~(TERMIOS.NLDLY)) | TERMIOS.NL0
        attr[3] = attr[3] & ~(TERMIOS.ICANON|TERMIOS.ECHO)
        termios.tcsetattr(0,TERMIOS.TCSANOW,attr)
        while 1:
            r,_,_ = select.select([0],[],[],0)
            if r:
                return os.read(0,1)
            else:
                return ''
    finally:
        termios.tcsetattr(0,TERMIOS.TCSANOW,oldattr)

season-to-taste-ly y'rs
M.

-- 
  please realize that the Common  Lisp community is more than 40 
  years old.  collectively, the community has already been where 
  every clueless newbie  will be going for the next three years.  
  so relax, please.                     -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list