On this page
  1. msvcrt
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Windows File Locking (Counterpart to Unix fcntl)
  7. Gotchas & Boundaries
  8. Common Functions

msvcrt

Prev: modulefinder | Up: stdlib_module | Next: multiprocessing
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — msvcrt
Tags: #public #python3 #stdlib


Import

import msvcrt

Overview

Windows-only interface to the Microsoft Visual C++ Runtime (MSVCRT) for low-level console keystrokes (kbhit(), getch(), getwch()), byte-range file locking (locking()), and CRT file-descriptor bridging (open_osfhandle(), get_osfhandle()). Use msvcrt when building interactive Windows terminal tools without curses or when locking files on Windows.

Quick Start

import sys

if sys.platform == "win32":
    import msvcrt

    # Non-blocking check for a keypress in a Windows console
    if msvcrt.kbhit():
        ch = msvcrt.getwch()
        print("Pressed:", repr(ch))

Implementation Walkthrough

1. Windows File Locking (Counterpart to Unix fcntl)

Where Unix code uses fcntl, Windows scripts can lock byte ranges via msvcrt.locking(fd, mode, nbytes):

import sys

def lock_first_byte(fh) -> None:
    if sys.platform == "win32":
        import msvcrt
        fh.seek(0)
        msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)

Gotchas & Boundaries

Common Functions

Linked from

Related notes