Use built-in input("Press Enter to continue...") when waiting for the Enter key portably across all operating systems, or use msvcrt.getch() on Windows and termios + tty on Linux/macOS (wrapped in a cross-platform helper or third-party readchar.readkey()) when you need to detect any single key immediately without pressing Enter.
Basic Example
import sys
# 1. Recommended (built-in, cross-platform): Wait for the Enter key
input("Press Enter to continue...")
# 2. Single-keypress pause WITHOUT pressing Enter (cross-platform stdlib helper)
def wait_for_any_key(prompt: str = "Press any key to continue...") -> str:
print(prompt, end="", flush=True)
if sys.platform == "win32":
import msvcrt
ch = msvcrt.getwch() # Returns Unicode str without echoing to console
else:
import termios
import tty
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd) # Disable line buffering & echo so 1 key returns immediately
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
print() # Move to next line after keypress
return ch
key = wait_for_any_key()
print(f"Key pressed: {key!r}")
Key Details & Edge Cases
- Always restore
termiosterminal settings inside atry / finally:block on Unix (Linux/macOS):- Calling
tty.setraw(fd)ortty.setcbreak(fd)disables canonical line buffering and terminal echoing at the OS file-descriptor level. If an exception orCtrl+Cinterrupts your script without restoringtermios.tcsetattr(fd, termios.TCSADRAIN, old_settings), the user’s shell prompt remains broken (typed commands become invisible) until they runreset.
- Calling
tty.setraw(fd)vs.tty.setcbreak(fd)on Linux/macOS (Ctrl+Chandling):tty.setraw(fd)interceptsCtrl+Cas raw character'\x03'instead of raisingKeyboardInterrupt, and turns\ninto raw\r\ncarriage returns.- Use
tty.setcbreak(fd)instead oftty.setraw(fd)if you still wantCtrl+Cto trigger normalKeyboardInterrupttermination and standard output newline translation.
- Special multi-byte keys (Arrow keys,
F1–F12,Delete) on Windows vs. Unix:- On Windows, pressing an arrow or function key makes
msvcrt.getwch()return a prefix ('\x00'or'\xe0') first—you must callmsvcrt.getwch()a second time to consume the scan code (otherwise the leftover second byte immediately triggers your next prompt!). - On Unix, arrow keys emit 3-byte ANSI escape sequences (
'\x1b[A'for Up Arrow). If you need full arrow/function key decoding without writing escape parsers, installreadchar(pip install readchar) and callreadchar.readkey().
- On Windows, pressing an arrow or function key makes
- Non-interactive environments (IDEs, background services, piped
stdin, Docker without-t):- Calling
termios.tcgetattr(sys.stdin.fileno())raisestermios.error: (25, 'Inappropriate ioctl for device')(orio.UnsupportedOperation) whenstdinis redirected from a file/pipe or run inside non-TTY runners. Guard raw terminal calls withif sys.stdin.isatty():and fall back toinput().
- Calling
- Avoid
os.system("pause"):os.system("pause")spawns an external shell subprocess, works only on Windows (failing withpause: command not foundon Linux/macOS), and introduces shell execution overhead.
Comparison of Keypress Waiting Methods in Python
| Method | Dependency | Waits for Any Key (No Enter)? | Cross-Platform? | Best Used When |
|---|---|---|---|---|
input("Press Enter...") (Simplest) |
Built-in | No (requires Enter) |
Yes | CLI scripts, installers, and debugging pauses where pressing Enter is fine. |
msvcrt.getwch() + termios/tty |
Stdlib (msvcrt / termios) |
Yes (single key, no echo) | Yes (with sys.platform branch) |
Zero-dependency CLI apps needing immediate single-key pauses on Windows, Linux, & macOS. |
readchar.readkey() |
3rd-party (pip install readchar) |
Yes (decodes arrows/Ctrl keys) | Yes | Interactive terminal menus needing cross-platform arrow keys, Escape, and special keys. |
keyboard.read_key() / pynput |
3rd-party (keyboard / pynput) |
Yes (global OS hook) | Mostly (needs root/permissions on Linux/macOS) | Detecting global hotkeys even when the terminal window is not in focus. |
os.system("pause") (Discouraged) |
Built-in (os) |
Yes | No (Windows cmd.exe only) |
Never—replace with input() or msvcrt.getwch(). |
You must log in or register to comment.
