Pure Python COM package
comtypes is a lightweight pure Python COM package based on the ctypes foreign function interface library. It allows defining, calling, and implementing custom and dispatch-based COM interfaces in pure Python. It currently requires Windows and Python 3.9 or later, with version 1.4.16 being the latest release. The project has an active release cadence with regular updates and maintenance.
Warnings
- breaking comtypes now requires Python 3.9 or later. Version 1.4.12 was the last release to officially support Python 3.8. Users on older Python versions must upgrade or use an older comtypes version.
- deprecated The `logutil.setup_logging` function has been deprecated. It should be replaced with standard Python `logging` module configuration.
- gotcha Generated type library wrapper modules (in `comtypes.gen`) can sometimes become corrupted or outdated, leading to `ImportError`, `NameError`, or `SyntaxError`.
- gotcha comtypes is a Windows-only library due to its reliance on the Component Object Model (COM), which is a Microsoft technology. It will not function on other operating systems.
- gotcha Direct usage of `ctypes.windll` or `ctypes.oledll` (from `ctypes`) should be modernized to `ctypes.WinDLL` or `ctypes.OleDLL` for improved robustness and clarity in current Python versions.
- gotcha Starting with Python 3.15, the internal handling of `IntFlag` (Flag) values is planned to change. This may affect enumeration types generated by `comtypes` from COM type libraries, potentially reinterpreting negative `IntFlag` members.
Install
-
pip install comtypes
Imports
- CreateObject
from comtypes.client import CreateObject
- GetModule
from comtypes.client import GetModule
- CoCreateInstance
from comtypes import CoCreateInstance
- GUID
from comtypes import GUID
Quickstart
import comtypes.client
import comtypes
# This example creates a COM object for the Microsoft Script Control,
# which might not be installed by default on all Windows systems.
# It's used here as a common demonstration of COM object creation.
try:
# Create an instance of a COM object using its ProgID
engine = comtypes.client.CreateObject("MSScriptControl.ScriptControl")
print("Successfully created MSScriptControl.ScriptControl object.")
# Use the COM object (example: evaluate a JScript expression)
engine.Language = "JScript"
result = engine.Eval("100 * 2")
print(f"Result of '100 * 2': {result}")
# If you need to access a specific interface by IID (Interface ID)
# from comtypes.GUID import GUID
# IID_IDispatch = GUID("{00020400-0000-0000-C000-000000000046}")
# disp_interface = engine.QueryInterface(IID_IDispatch)
# print(f"Queried for IDispatch interface: {disp_interface}")
except comtypes.COMError as e:
print(f"COM Error occurred: {e}")
print("This often means the requested COM object (e.g., MSScriptControl.ScriptControl)")
print("is not registered or available on your Windows system.")
except Exception as e:
print(f"An unexpected error occurred: {e}")