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

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?

Sent via Deja.com http://www.*-*-*.com/
Before you buy.



Mon, 26 May 2003 14:57:34 GMT  
 can i make sys.stdin.read() not wait?

Quote:

> 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



Mon, 26 May 2003 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. using sys.stdin.raw_input and sys.stdin.readline together in a platform independent way

2. non-blocking sys.stdin.read() on win32?

3. sys.stdin.read() HELP!

4. Error using sys.stdin.read()

5. Terminal reads and sys.stdin

6. Problems reading fra sys.stdin and later on duing raw_input

7. Chosing between sys.argv and sys.stdin

8. making wish on Windows NT read from stdin

9. It's not bad canned meat...

10. It's not bad canned meat...

11. It's not bad canned meat...

12. It's not bad canned meat...

 

 
Powered by phpBB® Forum Software