Non-blocking login in python 3

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

Something like this (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 vs cooked mode. Ready mode is the default terminal behavior in which strings buffer stdin, raw mode makes characters available to the input stream as they are entered.

What I would like is a platform independent way to read from stdin and not block if there is no data to read. Again, I don't have to hit enter to make the characters stream available. I just don't want the program to stop completely when there is nothing in stdin.

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

I would rather not use heavy weight solutions like threads or subprocesses.

+3


source to share





All Articles