Search code examples
pythonpython-3.xwindowstimeoutuser-input

Timeout a input(prompt) after 60 seconds of inactivity from user[python]


activity = input("Enter the message:")

if no input from user it should be auto-stopped , giving a message no activity from the user. i am a newbie to python. any help is appreciated.


Solution

  • Do it like this with threads:

    import threading
    import queue
    
    result_queue = queue.Queue()
    def input_target(queue):
      queue.put(input('Enter the message:'))
    threading.Thread(target=input_target, daemon=True, args=(result_queue,)).start()
    result = None
    try:
      result = result_queue.get(timeout=1)
    except queue.Empty:
      result = None
    print([result])
    

    Please note that the thread continues running after the timeout has been reached, so subsequent reads from stdin won't work.

    Alternatively, if you want to make subsequent reads work, then you can try calling select.select (with a timeout) and os.read(0, ...) in a loop, but that doesn't work on Windows (because select.select on Windows requires that the filehandle is a socket, which it isn't for console input).