6

I would like a cross platform way to read input from stdin in a non blocking way.

Something like this (which is how non-blocking sockets do it):

while True
    try:
        string = input("> ")
    except BlockingIOError:
        pass
    else:
        print(f"you typed {string}")

I am not asking about raw mode vs cooked mode. Cooked mode is the default terminal behavior which line buffers stdin, raw mode makes characters available to the input stream as you type them.

What I would like is a platform independent way of reading from stdin and not have it block if there is no data to be read yet. Again I don't care about having to press enter to make the chars available to the stream. I just don't want the program to halt completely when there's nothing in stdin.

I would also be happy with an asynchronous approach. Or something that throws a BlockingIOError like my example above. Or something like Java's Scanner.hasNextLine() which returns a bool representing whether or not stdin has data to be read.

I'd prefer not to use heavy weight solutions like threading or subprocesses.

nickeb96
  • 789
  • 1
  • 10
  • 16

0 Answers0