Using a select call is shorter, and should be much more portable

import sys, select

print "You have ten seconds to answer!"

i, o, e = select.select( [sys.stdin], [], [], 10 )

if (i):
  print "You said", sys.stdin.readline().strip()
else:
  print "You said nothing!"
Answer from Pontus on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-wait-time-wait-for-input
Python wait time, wait for user input | DigitalOcean
August 3, 2022 - When we run this program, there will be 5 seconds delay between first print statement and second print statement. Sometimes we want to get some inputs from the user through the console. We can use input() function to achieve this. In this case, the program will wait indefinitely for the user input.
Discussions

How to set input time limit for user in game?
I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want ... More on discuss.python.org
🌐 discuss.python.org
0
0
December 2, 2022
Wait for an input with a timeout... asked for the billionth time
You won't ever make this work using input() in Windows. You will have to make your own function that checks for keyboard presses. Try this: #!/usr/bin/python # timed input function # Windows only # python2 or python3 # this does not deal with arrow keys. # this probably won't work in IDLE from __future__ import print_function from msvcrt import kbhit, getwch import time import sys def print_flush(*args): print(*args, end='') sys.stdout.flush() def timed_input(prompt='', timeout=None): if timeout is None: return input(prompt) print_flush(prompt) start = time.time() response = '' while time.time() - start < timeout: if kbhit(): char = getwch() if char == '\r': break elif char == '\x08': # backspace if response: print_flush(char, char) response = response[:-1] else: print_flush(char) response += char time.sleep(0.01) else: response = None print() return response ### Test / Demo code: def main(): key = 'pass' time_limit = 5 # in seconds validation = timed_input('Enter your verification code here: ', time_limit) print(validation) if validation == key: print('Success! You may continue.') elif validation is None: print('you have exceeded your time limit') else: print('Wrong verification code. Access Denied.') if __name__ == '__main__': main() More on reddit.com
🌐 r/learnpython
2
2
May 3, 2019
Python wait x secs for a key and continue execution if not pressed - Stack Overflow
I'm looking for a code snippet/sample which performs the following: Display a message like "Press any key to configure or wait X seconds to continue" Wait, for example, 5 seconds and con... More on stackoverflow.com
🌐 stackoverflow.com
How do I make a loop wait one second before continuing? I'm a beginner in Python and am trying to make a script that counts, but only every one second.
import time time.sleep(1) More on reddit.com
🌐 r/learnpython
4
1
July 28, 2023
🌐
GitHub
gist.github.com › r0dn0r › d75b22a45f064b24e42585c4cc3a30a0
Python: wait for input(), else continue after x seconds · GitHub
If there is input, then it will return a list of objects from which input can be read, and only then you read the input. Here: def _wait_for_enter(channel: queue.Queue, timeout: int = None): (rlist, wlist, xlist) = select([stdin], [], [], timeout) if len(rlist): line = stdin.readline() channel.put(line)
🌐
Centron
centron.de › startseite › python wait time & user input handling – essential guide
Python Wait Time & User Input Handling - Essential Guide
February 6, 2025 - sec = input('Let us wait for user input. Let me know how many seconds to sleep now.\n') print('Going to sleep for', sec, 'seconds.') time.sleep(int(sec)) print('Enough of sleeping, I Quit!') Python Wait Time & User Input Handling – Essential Guide
🌐
Real Python
realpython.com › python-sleep
Python sleep(): How to Add Time Delays to Your Code – Real Python
August 1, 2023 - In this tutorial, you'll learn how to add time delays to your Python programs. You'll use decorators and the built-in time module to add Python sleep() calls to your code. Then, you'll discover how time delays work with threads, asynchronous functions, and graphical user interfaces.
🌐
Python.org
discuss.python.org › python help
How to set input time limit for user in game? - Python Help - Discussions on Python.org
December 2, 2022 - I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want ...
🌐
Python Central
pythoncentral.io › pythons-time-sleep-pause-wait-sleep-stop-your-code
Python's time.sleep() - Pause, Stop, Wait or Sleep your Python Code | Python Central
December 30, 2021 - secs - The number of seconds the Python program should pause execution. This argument should be either an int or float. ... Here we have instructed the system to wait for five seconds through the first command and then wait for three hundred ...
🌐
Reddit
reddit.com › r/learnpython › wait for an input with a timeout... asked for the billionth time
r/learnpython on Reddit: Wait for an input with a timeout... asked for the billionth time
May 3, 2019 -

Apparently this is an unbelievably common issue that I have just never found a running answer for. I have tried nearly every response on here and stackoverflow, and none have worked. So this seems to be the one that should work with Windows, Python 3.7, but it doesn't.

from threading import Timer

timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
t.cancel()

Mine just sits and waits forever, then no matter the input gives the timeout error.

Find elsewhere
🌐
PyPI
pypi.org › project › pytimedinput
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
EyeHunts
tutorial.eyehunts.com › home › python wait | how to python wait for input
Python Wait | How to Python Wait for Input from user example - EyeHunts
May 18, 2021 - import time name = input('Please Enter Your Name \n') print('Wait ', 5, 'seconds for reply.') time.sleep(5) print('Hi', name, ', How are you, I am bot!') ... It can your interview question for python programming.
🌐
Code Institute
codeinstitute.net › blog › coding › how to wait in python
How to Wait in Python - Code Institute Global
September 1, 2023 - If reading is specified, this creates a new instance of Interactive Console and sets dreadful as the InteractiveConsole.raw input() method. system(“pause”) is a method in the OS module. We can have a Python application wait till a key is pressed using this method.
🌐
GitHub
gist.github.com › atupal › 5865237
Keyboard input with timeout in Python · GitHub
Keyboard input with timeout in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Linux Hint
linuxhint.com › python_pause_user_input
Python Pause For User Input – Linux Hint
sleep() method can be used to pause the user input for a certain period of time. In the following script, a simple addition task is given for the user. sleep() method is used here to wait for the user for 5 seconds before typing the answer. Next, if the condition is used to check the answer ...
🌐
iO Flood
ioflood.com › blog › python-wait
Python Sleep Methods | How to Make Code Pause or Wait
August 21, 2024 - In this example, time.sleep(2) makes Python wait for 2 seconds between printing ‘Start’ and ‘End’. Pausing execution, or making a program wait, is a fundamental concept in programming. It allows you to control the flow of your program and coordinate actions. For example, you might want to wait for a user to enter input...
Top answer
1 of 7
35

The signal.alarm function, on which @jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on threading.Timer instead, using thread.interrupt_main to send a KeyboardInterrupt to the main thread from the timer thread. I.e.:

import thread
import threading

def raw_input_with_timeout(prompt, timeout=30.0):
    print(prompt, end=' ')    
    timer = threading.Timer(timeout, thread.interrupt_main)
    astring = None
    try:
        timer.start()
        astring = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return astring

this will return None whether the 30 seconds time out or the user explicitly decides to hit control-C to give up on inputting anything, but it seems OK to treat the two cases in the same way (if you need to distinguish, you could use for the timer a function of your own that, before interrupting the main thread, records somewhere the fact that a timeout has happened, and in your handler for KeyboardInterrupt access that "somewhere" to discriminate which of the two cases occurred).

Edit: I could have sworn this was working but I must have been wrong -- the code above omits the obviously-needed timer.start(), and even with it I can't make it work any more. select.select would be the obvious other thing to try but it won't work on a "normal file" (including stdin) in Windows -- in Unix it works on all files, in Windows, only on sockets.

So I don't know how to do a cross-platform "raw input with timeout". A windows-specific one can be constructed with a tight loop polling msvcrt.kbhit, performing a msvcrt.getche (and checking if it's a return to indicate the output's done, in which case it breaks out of the loop, otherwise accumulates and keeps waiting) and checking the time to time out if needed. I cannot test because I have no Windows machine (they're all Macs and Linux ones), but here the untested code I would suggest:

import msvcrt
import time

def raw_input_with_timeout(prompt, timeout=30.0):
    print(prompt, end=' ')    
    finishat = time.time() + timeout
    result = []
    while True:
        if msvcrt.kbhit():
            result.append(msvcrt.getche())
            if result[-1] == '\r':   # or \n, whatever Win returns;-)
                return ''.join(result)
            time.sleep(0.1)          # just to yield to other processes/threads
        else:
            if time.time() > finishat:
                return None

The OP in a comment says he does not want to return None upon timeout, but what's the alternative? Raising an exception? Returning a different default value? Whatever alternative he wants he can clearly put it in place of my return None;-).

If you don't want to time out just because the user is typing slowly (as opposed to, not typing at all!-), you could recompute finishat after every successful character input.

2 of 7
13

I found a solution to this problem in a blog post. Here's the code from that blog post:

import signal

class AlarmException(Exception):
    pass

def alarmHandler(signum, frame):
    raise AlarmException

def nonBlockingRawInput(prompt='', timeout=20):
    signal.signal(signal.SIGALRM, alarmHandler)
    signal.alarm(timeout)
    try:
        text = raw_input(prompt)
        signal.alarm(0)
        return text
    except AlarmException:
        print '\nPrompt timeout. Continuing...'
    signal.signal(signal.SIGALRM, signal.SIG_IGN)
    return ''

Please note: this code will only work on *nix OSs.