Question:
I’m writing a simple terminal-based program in Python and noticed unexpected behavior when combining time.sleep() and input().

Here is a minimal example:

import time print("Starting") time.sleep(3) input()

If I type characters while the program is in the time.sleep(3) call, those characters are immediately read by input() once the sleep finishes. I expected input() to only accept input typed after it is called.

Why does this happen? Is the input being handled by Python, or is it buffered by the terminal or operating system? What is the correct way to prevent previously typed input from being consumed by input() in terminal-based programs?

I’m especially interested in understanding the underlying reason for this behavior, not just a workaround.

Platonic09's user avatar

New contributor

Platonic09 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

The O/S is buffering the keyboard.

The Python interpreter doesn't even see the input() line until it awakens from the sleep(3).

Side note: Python's sleep calls the O/S which suspends the thread. Python is not active at all during the sleep.

Raymond Hettinger's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.