[Python] How does one read from stdin with a timeout in python?

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to read from stdin and get None (or some other defined value) should the user not input any text after a predefined timeout. However, when I tried the below code, the script just hung indefinitely at the Enter some text: point and does not time out at 5 seconds, as it should.

    import os
    import tty
    import sys
    import time

    fd = sys.stdin.fileno()

    tty.setraw(fd)

    print("Enter some text:", end=' ', flush=True)
    t1 = time.time()
    d = os.read(fd, 5)
    print("Time taken:", time.time() - t1, "d:", d)


    Htop (process monitor) tells me that the python process running my scrip is not in disk sleep (as I would have thought it would) and when I enter a character the Time taken: string printed at the end often exceeds 5 seconds. I am aware that I am only able to read user input one char at a time.

    Continue reading...

Compartilhe esta Página