Pressed Key
Waiting for Input
Programming Guide
Keyboard Events
Software Development

How do I wait for a pressed key?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Waiting for a pressed key sounds simple, but the correct solution depends on the kind of program you are writing. Terminal applications, games, and GUI apps handle keyboard input differently, so the main question is whether you need line input, a single key without Enter, or event-driven key handling.

Decide What "Wait for a Key" Means

Many beginners really mean "pause until the user presses Enter." In that case, a normal line-input function is enough:

python
input("Press Enter to continue...")

That blocks until Enter is pressed and is perfectly fine for scripts, demos, and command-line tools. It does not detect arbitrary keys immediately. If you need a single key press such as q, y, or Escape, you need a lower-level API.

Waiting for a Single Key in a Console on Windows

On Windows, Python’s msvcrt module is the simplest built-in approach for reading one key without waiting for Enter:

python
1import msvcrt
2
3print("Press any key to continue...")
4key = msvcrt.getch()
5print(f"You pressed: {key!r}")

getch() returns raw bytes, which is often exactly what you want for simple key handling. If you want a decoded character when possible:

python
1import msvcrt
2
3print("Press any key...")
4key = msvcrt.getwch()
5print(f"You pressed: {key}")

This is a good fit for console programs that run only on Windows.

Waiting for a Single Key in a Unix-Like Terminal

On macOS and Linux, terminals usually buffer input until Enter unless you switch the terminal into raw mode. Python can do that with termios and tty:

python
1import sys
2import termios
3import tty
4
5
6def read_single_key():
7    fd = sys.stdin.fileno()
8    old_settings = termios.tcgetattr(fd)
9    try:
10        tty.setraw(fd)
11        return sys.stdin.read(1)
12    finally:
13        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
14
15
16print("Press any key...")
17key = read_single_key()
18print(f"You pressed: {key}")

The important part is restoring the old terminal settings in the finally block. If you forget that, the terminal may behave strangely after the program exits.

Event-Driven Applications Use Handlers, Not Blocking Reads

GUI applications should usually not block the main thread waiting for input. Instead, they register a key event handler and let the framework call it when the user presses something.

Here is a small tkinter example:

python
1import tkinter as tk
2
3
4def on_key(event):
5    print(f"Pressed: {event.keysym}")
6
7
8root = tk.Tk()
9root.title("Key Example")
10root.bind("<KeyPress>", on_key)
11root.mainloop()

This pattern is common in GUI frameworks because the application needs to keep processing paint events, mouse events, and timers while waiting for keyboard input.

Cross-Platform Convenience Libraries

If you need richer key handling, a library can simplify the platform differences. For example, pynput can listen for keyboard events:

python
1from pynput import keyboard
2
3
4def on_press(key):
5    print(f"Pressed: {key}")
6    return False
7
8
9with keyboard.Listener(on_press=on_press) as listener:
10    listener.join()

This is convenient, but external libraries add dependencies and may behave differently across terminals, remote sessions, and operating systems.

Choosing the Right Approach

A useful rule is:

  • use input() when Enter is enough
  • use platform-specific console APIs for immediate single-key reads
  • use event callbacks in GUI or game loops
  • use third-party libraries only when built-in tools are too limited

That keeps the code aligned with the way the environment actually handles input.

Common Pitfalls

The most common mistake is using input() when the real requirement is "react immediately to one key." input() waits for Enter, so it is the wrong tool for menus, games, or interactive prompts.

Another pitfall is writing platform-specific code without realizing it. msvcrt is Windows-only, while termios and tty are for Unix-like systems. If your script must run everywhere, you need conditional logic or a library.

In terminal code, developers also sometimes forget to restore terminal state after enabling raw input. That can leave the shell in an unusable state until it is reset.

Finally, blocking reads inside GUI code freeze the interface. Event-driven frameworks expect handlers, not loops that wait on stdin.

Summary

  • The correct way to wait for a key depends on whether you need Enter, a single raw key, or an event callback.
  • 'input() is fine for "Press Enter to continue" style pauses.'
  • Use msvcrt on Windows or termios with tty on Unix-like systems for immediate single-key console input.
  • In GUI apps, register key handlers instead of blocking the main thread.
  • Restore terminal settings carefully when using raw input mode.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions