On this page
  1. winreg
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Writing Per-User Settings Safely
  7. Gotchas & Boundaries
  8. Common Functions

winreg

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


Import

import winreg

Overview

Windows-only interface to the Windows Registry (OpenKey(), QueryValueEx(), SetValueEx(), EnumKey(), EnumValue()). Use winreg to read installed software settings, OS theme/proxy preferences, or file associations on Windows without shelling out to reg.exe.

Quick Start

import sys

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

    with winreg.OpenKey(
        winreg.HKEY_LOCAL_MACHINE,
        r"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
    ) as key:
        product_name, reg_type = winreg.QueryValueEx(key, "ProductName")
        print(product_name)

Implementation Walkthrough

1. Writing Per-User Settings Safely

Write to HKEY_CURRENT_USER (which doesn't require administrator privileges) using CreateKeyEx() as a context manager so handles always close:

import sys

def save_user_setting(subkey: str, name: str, value: str) -> None:
    if sys.platform != "win32":
        return
    import winreg
    with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, subkey, 0, winreg.KEY_SET_VALUE) as key:
        winreg.SetValueEx(key, name, 0, winreg.REG_SZ, value)

Gotchas & Boundaries

Common Functions

Linked from

Related notes