msvcrt
The Python msvcrt module exposes a subset of the Microsoft Visual C++ runtime library on Windows. It provides low-level access to console input, wide-character I/O, file locking, and file-descriptor bridging routines that are otherwise unavailable from cross-platform modules.
This module is only present on Windows, and several higher-level standard library modules, including getpass, rely on it for their Windows-specific code paths.
Here’s a quick example:
>>> import msvcrt
>>> msvcrt.kbhit()
0
>>> msvcrt.getch()
b'a'
The call to kbhit() reports that no key is currently buffered, and getch() blocks until the user presses a key, returning the corresponding byte without echoing it to the console.
Key Features
- Reads individual keystrokes without waiting for a newline or echoing to the screen
- Polls the console for pending input with
kbhit() - Provides wide-character Unicode counterparts for all console I/O functions
- Locks and unlocks byte ranges in an open file through
locking() - Converts between Python file descriptors and raw Windows
HANDLEvalues - Controls the text or binary translation mode of an open file descriptor with
setmode()
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
msvcrt.kbhit() |
Function | Returns a nonzero value if a keystroke is waiting to be read |
msvcrt.getch() |
Function | Reads a single keypress as a bytes object without echoing it |
msvcrt.getche() |
Function | Reads a single keypress and echoes it to the console |
msvcrt.getwch() |
Function | Reads a single keypress as a Unicode character without echoing it |
msvcrt.putch() |
Function | Writes a single byte to the console without buffering |
msvcrt.putwch() |
Function | Writes a single Unicode character to the console without buffering |
msvcrt.ungetch() |
Function | Pushes a byte back into the console input buffer |
msvcrt.locking() |
Function | Locks or unlocks a byte range in an open file |
msvcrt.setmode() |
Function | Switches a file descriptor between text and binary translation modes |
msvcrt.get_osfhandle() |
Function | Returns the underlying Windows handle for a given file descriptor |
msvcrt.open_osfhandle() |
Function | Wraps a raw Windows handle in a C runtime file descriptor |
Examples
Reading a single keystroke without echo from the console:
>>> import msvcrt
>>> key = msvcrt.getch()
>>> key
b'q'
Polling for input inside a non-blocking loop:
poll_keys.py
import msvcrt
import time
print("Press any key to stop...")
while not msvcrt.kbhit():
print("working", end="\r", flush=True)
time.sleep(0.5)
print(f"\nPressed: {msvcrt.getch()!r}")
Reading a wide character to support non-ASCII input:
>>> import msvcrt
>>> msvcrt.getwch()
'n'
Locking a byte range in an open file with locking():
lock_range.py
import msvcrt
with open("data.txt", "r+b") as fp:
fd = fp.fileno()
msvcrt.locking(fd, msvcrt.LK_NBLCK, 100)
try:
fp.write(b"updated region")
finally:
fp.seek(0)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 100)
The LK_NBLCK flag attempts the lock without blocking and raises OSError if another process already holds it, while LK_LOCK retries up to ten times at one-second intervals.
Obtaining the raw Windows handle for a file descriptor:
>>> import msvcrt
>>> import sys
>>> msvcrt.get_osfhandle(sys.stdout.fileno())
7
Common Use Cases
The most common tasks for msvcrt include:
- Implementing Windows-friendly password prompts that hide characters as the user types
- Building interactive command-line programs that react to single keystrokes
- Polling for user input without blocking a running animation or progress display
- Coordinating concurrent writers by locking byte ranges in a shared data file
- Interoperating with Windows APIs that require a raw
HANDLErather than a Python file object
Real-World Example
Consider a tiny Windows password prompt that reads characters one at a time, displays an asterisk for each keystroke, and stops when the user presses Enter. The msvcrt module provides every piece needed to build it, from getwch() for wide-character input to putwch() for immediate echo:
prompt_password.py
import msvcrt
def prompt_password(label="Password: "):
print(label, end="", flush=True)
buffer = []
while True:
char = msvcrt.getwch()
if char in ("\r", "\n"):
msvcrt.putwch("\n")
return "".join(buffer)
if char == "\x03":
raise KeyboardInterrupt
if char == "\b":
if buffer:
buffer.pop()
msvcrt.putwch("\b")
msvcrt.putwch(" ")
msvcrt.putwch("\b")
continue
buffer.append(char)
msvcrt.putwch("*")
if __name__ == "__main__":
secret = prompt_password()
print(f"Captured {len(secret)} characters.")
Run the script from a Windows command prompt:
PS> python prompt_password.py
Password: ********
Captured 8 characters.
When the script runs in a Windows console, each keystroke is captured instantly without being echoed by the terminal. The helper shows a masked asterisk, handles backspace by erasing the last character on screen, and returns the assembled string once Enter is pressed. This is the same general approach used by getpass.getpass() when it runs on Windows.
Related Resources
Tutorial
How to Read User Input From the Keyboard in Python
Reading user input from the keyboard is a valuable skill for a Python programmer, and you can create interactive and advanced programs that run on the terminal. In this tutorial, you'll learn how to create robust user input programs, integrating error handling and multiple entries.
For additional information on related topics, take a look at the following resources:
- Your Python Coding Environment on Windows: Setup Guide (Tutorial)
- The Python Rich Package: Unleash the Power of Console Text (Tutorial)
- Basic Input and Output in Python (Tutorial)
- Build Command-Line Interfaces With Python's argparse (Tutorial)
- Python Command-Line Arguments (Tutorial)
- Reading User Input From the Keyboard With Python (Course)
- Your Python Coding Environment on Windows: Setup Guide (Quiz)
- Unleashing the Power of the Console With Rich (Course)
- Reading Input and Writing Output in Python (Course)
- Basic Input and Output in Python (Quiz)
- Building Command Line Interfaces With argparse (Course)
- Build Command-Line Interfaces With Python's argparse (Quiz)
- Command Line Interfaces in Python (Course)
By Leodanis Pozo Ramos • Updated May 7, 2026