HELP Non-Blocking reads from sys.stdin in Windows.

Miki Tebeka miki.tebeka at zoran.com
Tue Dec 28 15:38:06 EST 2004


Hello Barr,

> I am in real need of a way to perform non blocking reads from sys.stdin on
> windows. I have looked every where for an answer but but with no luck. I
> beleive there there must be a way of doing this, can some one  please help
> asap.
Warning: The below code wasn't tested at all...

-------------------------------
from Queue import Queue, Empty
from sys import stdin
from threading import Thread

# Reading from empty stdin error
class EmptyError(Exception): pass 

# Input queue
_queue = Queue()

def produce():
    '''Read one char at a time from stdin and place in _queue'''
    try:
        while 1:
            c = stdin.read(1) # Read one char
            if not c: # EOF
                _queue.put(EOFError, 1)
                break
            _queue.put(c, 1)
    except EOFError, e:
        _queue.put(EOFError)

# Start the thread
t = Thread(target=produce)
t.setDaemon(1) # Don't inhibit interperter exit
t.start() # Start thread

def get():
    '''Get one item from queue.

    Might raise EmptyError if queue is empty or EOFError of end of input
    '''
    try:
        val = _queue.get(0)
        if val is EOFError:
            raise EOFError
        return val
    except Empty:
        raise EmptyError

def is_empty():
    '''Tell if no input is ready'''
    return _queue.empty()

-------------------------------

HTH.
--
------------------------------------------------------------------------
Miki Tebeka <miki.tebeka at zoran.com>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys



More information about the Python-list mailing list