Pure Python COM package

1.4.16 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to create and interact with a COM object using `comtypes.client.CreateObject`. It attempts to instantiate the `MSScriptControl.ScriptControl` object, which provides scripting capabilities, and then executes a simple JavaScript expression. Error handling is included for when the COM object might not be available on the system.

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}")

view raw JSON →