How to Set an Input Time Limit in Python
Sometimes your Python program needs to move on if the user doesn't respond quickly enough: think timed quizzes, command-line prompts with deadlines, or automated scripts that cannot hang forever waiting for input. Setting a time limit on user input solves this problem by automatically timing out after a specified number of seconds.
In this guide, you will learn four different ways to set an input time limit in Python, each with its own strengths and platform considerations. By the end, you will know which approach fits your project best.
Using the inputimeout Module
The inputimeout library is a lightweight, cross-platform package designed specifically for timed input. It is the simplest option and works on Windows, macOS, and Linux.
Installation
pip install inputimeout
Example
from inputimeout import inputimeout, TimeoutOccurred
try:
answer = inputimeout(prompt="Name your best friend: ", timeout=5)
print(f"You answered: {answer}")
except TimeoutOccurred:
print("Time is up! You did not answer in time.")
Output (if the user answers in time):
Name your best friend: Alice
You answered: Alice
Output (if the user does not answer within 5 seconds):
Name your best friend:
Time is up! You did not answer in time.
The inputimeout() function behaves exactly like the built-in input(), but it accepts an additional timeout parameter (in seconds). When the timeout expires, it raises TimeoutOccurred.
Choose inputimeout when you need a quick, cross-platform solution and don't mind adding an external dependency. It is the most beginner-friendly option.
A common mistake is catching a generic Exception instead of TimeoutOccurred. While that technically works, it can silently swallow unrelated errors and make debugging harder. Always catch TimeoutOccurred explicitly:
# ❌ Too broad: hides real bugs
except Exception:
print("Something happened")
# ✅ Specific: only catches the timeout
except TimeoutOccurred:
print("Time is up!")
Using the signal Module (Unix/macOS Only)
The signal module is part of the Python standard library and lets you schedule an alarm signal (SIGALRM) that interrupts the running program after a given number of seconds.
Example
import signal
def timeout_handler(signum, frame):
raise TimeoutError("Time is up!")
# Register the handler for the alarm signal
signal.signal(signal.SIGALRM, timeout_handler)
# Set the alarm for 10 seconds
signal.alarm(10)
try:
print("Who is your best friend?")
print("You have 10 seconds to answer!\n")
answer = input("Enter your answer: ")
# Disable the alarm after a successful answer
signal.alarm(0)
print(f"\nYou answered: {answer}")
except TimeoutError:
print("\nYour time is over!")
Output (if the user answers in time):
Who is your best friend?
You have 10 seconds to answer!
Enter your answer: Bob
You answered: Bob
Output (if the timeout expires):
Who is your best friend?
You have 10 seconds to answer!
Enter your answer:
Your time is over!
The key steps are:
- Register a handler with
signal.signal()that raises an exception when the alarm fires. - Start the countdown with
signal.alarm(seconds). - Cancel the alarm with
signal.alarm(0)once the user provides input.
signal.SIGALRM is only available on Unix-based systems (Linux, macOS). This approach will not work on Windows. If you need cross-platform support, use inputimeout or the threading approach instead.
Using the select Module (Unix/macOS Only)
The select module monitors file descriptors for I/O readiness. You can use it to check whether stdin has data available within a given time window.
Example
import sys
import select
timeout_seconds = 10
print("Who is your best friend?")
print(f"You have {timeout_seconds} seconds to answer!\n")
# Wait until stdin is ready or the timeout expires
ready, _, _ = select.select([sys.stdin], [], [], timeout_seconds)
if ready:
answer = sys.stdin.readline().strip()
print(f"\nYou answered: {answer}")
else:
print("\nYour time is over!")
Output (if the user answers in time):
Who is your best friend?
You have 10 seconds to answer!
Alice
You answered: Alice
Output (if the timeout expires):
Who is your best friend?
You have 10 seconds to answer!
Your time is over!
select.select() returns three lists. The first list contains file descriptors that are ready to be read. If it is empty, the timeout expired before any input arrived.
Like signal.SIGALRM, the select module's support for sys.stdin monitoring is limited on Windows. On Windows, select only works with sockets, not with standard input.
Using the threading Module (Cross-Platform)
The threading module is part of the standard library and works on all platforms, including Windows. The idea is to start a background timer that prints a message (or performs an action) when time runs out.
Example
from threading import Timer
timeout_seconds = int(input("Set time limit in seconds: "))
print("\nWho is your best friend?")
print(f"You have {timeout_seconds} seconds to answer!\n")
def on_timeout():
print("\nYour time is over! Press Enter to exit.")
# Start a background timer
timer = Timer(timeout_seconds, on_timeout)
timer.start()
answer = input("Enter your answer: ")
# Cancel the timer if the user answered in time
timer.cancel()
print(f"You answered: {answer}")
Output (if the user answers in time):
Set time limit in seconds: 10
Who is your best friend?
You have 10 seconds to answer!
Enter your answer: Charlie
You answered: Charlie
Output (if the timeout expires before the user answers):
Set time limit in seconds: 5
Who is your best friend?
You have 5 seconds to answer!
Enter your answer:
Your time is over! Press Enter to exit.
input()The threading.Timer runs the callback function in a separate thread, but it cannot interrupt the input() call that is blocking in the main thread. The user will still need to press Enter for the program to continue after the timeout message is displayed. If you need input() to be truly interrupted, prefer the signal method on Unix or inputimeout for cross-platform use.
Comparison of Methods
| Method | Cross-Platform | Standard Library | Interrupts input() |
|---|---|---|---|
inputimeout | ✅ Yes | ❌ No (pip install) | ✅ Yes |
signal | ❌ Unix/macOS only | ✅ Yes | ✅ Yes |
select | ❌ Unix/macOS only | ✅ Yes | ✅ Yes |
threading.Timer | ✅ Yes | ✅ Yes | ❌ No |
Summary
Setting an input time limit in Python can be achieved in several ways depending on your target platform and requirements:
inputimeout: the easiest and most portable solution. Ideal for most use cases.signal: a clean, standard-library approach that truly interrupts input, but only works on Unix/macOS.select: useful when you want low-level I/O monitoring, again limited to Unix/macOS.threading.Timer: cross-platform and requires no extra packages, but cannot forcefully cancel a blockinginput()call.
For most projects, inputimeout is the recommended choice due to its simplicity and cross-platform compatibility. If you cannot use external packages and you are on a Unix system, the signal module is the best standard-library alternative.