Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Windows registry access using Python (winreg)
Python provides excellent support for OS-level programming through its extensive module library. The winreg module allows Python programs to access and manipulate the Windows registry, which stores configuration settings and system information.
The Windows registry is organized in a hierarchical structure with keys and values. Python's winreg module provides functions to connect to, read from, and write to registry keys.
Basic Registry Access
First, import the winreg module and establish a connection to the registry ?
import winreg
# Connect to the registry
access_registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
# Open a specific key
access_key = winreg.OpenKey(access_registry, r"SOFTWARE\Microsoft\Windows\CurrentVersion")
# Enumerate through subkeys
for n in range(20):
try:
x = winreg.EnumKey(access_key, n)
print(x)
except:
break
# Close the key
winreg.CloseKey(access_key)
The output shows the subkeys under the CurrentVersion registry path ?
ApplicationFrame AppModel Appx Audio Authentication AutoRotation BITS Casting ClosedCaptioning CloudExperienceHost Component Based Servicing ...
Reading Registry Values
You can also read specific values from registry keys ?
import winreg
try:
# Open registry key
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows\CurrentVersion")
# Read a specific value
value, reg_type = winreg.QueryValueEx(key, "ProductName")
print(f"Product Name: {value}")
# Close the key
winreg.CloseKey(key)
except FileNotFoundError:
print("Registry key not found")
except Exception as e:
print(f"Error: {e}")
Common Registry Hives
| Constant | Description | Use Case |
|---|---|---|
HKEY_CURRENT_USER |
Current user settings | User-specific configuration |
HKEY_LOCAL_MACHINE |
System-wide settings | Hardware and software info |
HKEY_CLASSES_ROOT |
File associations | File type mappings |
Key Functions
-
ConnectRegistry()? Connects to a registry hive -
OpenKey()? Opens a registry key for access -
EnumKey()? Enumerates subkeys of an open key -
QueryValueEx()? Retrieves the value of a registry entry -
CloseKey()? Closes a registry key handle
Conclusion
The winreg module provides comprehensive access to Windows registry data. Always close registry keys after use and handle exceptions properly when accessing system-level resources.
