CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-comtypes

Pure Python COM package for Windows COM automation and interoperability

88

0.98x
Overview
Eval results
Files

client-api.mddocs/

Client API

High-level functions for consuming COM objects and services. Provides convenient wrappers around low-level COM operations, automatic type library processing, event handling, and support for both early-bound and late-bound programming models.

Capabilities

Object Creation

High-level functions for creating and accessing COM objects with automatic interface detection and type library integration.

def CreateObject(progid, clsctx=None, machine=None, interface=None, dynamic=False):
    """
    Create COM object from ProgID with automatic wrapper generation.
    
    Args:
        progid (str): Programmatic identifier (e.g., "Excel.Application")
        clsctx (int, optional): Class context (defaults to CLSCTX_ALL)
        machine (str, optional): Remote machine name for DCOM
        interface (type, optional): Specific interface to query for
        dynamic (bool): Use dynamic dispatch wrapper if True
    
    Returns:
        COM object wrapper with strongly-typed methods and properties
        or Dispatch wrapper if dynamic=True
    
    Raises:
        COMError: If object creation fails
    """

def GetActiveObject(progid, interface=None, dynamic=False):
    """
    Get existing active COM object by ProgID.
    
    Args:
        progid (str): Programmatic identifier
        interface (type, optional): Specific interface to query for
        dynamic (bool): Use dynamic dispatch wrapper if True
    
    Returns:
        Active COM object wrapper
    
    Raises:
        COMError: If no active object found
    """

def CoGetObject(displayname, interface=None, dynamic=False):
    """
    Create object from moniker display name.
    
    Args:
        displayname (str): Moniker display name (e.g., file path, URL)
        interface (type, optional): Specific interface to query for
        dynamic (bool): Use dynamic dispatch wrapper if True
    
    Returns:
        COM object from moniker
    """

def GetClassObject(clsid, clsctx=None, machine=None):
    """
    Get class factory object for COM class.
    
    Args:
        clsid (GUID or str): Class identifier
        clsctx (int, optional): Class context
        machine (str, optional): Remote machine name
    
    Returns:
        IClassFactory interface for creating object instances
    """

Interface Management

Functions for working with COM interfaces and automatic interface detection.

def GetBestInterface(punk):
    """
    Get the most specific interface for a COM object.
    Attempts to find strongly-typed interface wrapper.
    
    Args:
        punk (IUnknown): COM object
    
    Returns:
        Most specific interface wrapper available
    """

# Alias for GetBestInterface
wrap = GetBestInterface

def _manage(obj, clsid, interface):
    """
    Internal function for COM object lifecycle management.
    
    Args:
        obj: COM object to manage
        clsid (GUID): Class identifier
        interface (type): Interface type
    
    Returns:
        Managed COM object
    """

Type Library Processing

Generate and manage Python wrapper modules from COM type libraries.

def GetModule(tlib):
    """
    Generate or retrieve Python wrapper module for type library.
    
    Args:
        tlib (str or ITypeLib): Type library path, ProgID, or ITypeLib interface
    
    Returns:
        Python module containing strongly-typed interface wrappers
    
    Raises:
        COMError: If type library cannot be loaded or processed
    """

Constants Access

Access to type library constants through a convenient interface.

class Constants:
    """Provides access to constants defined in type libraries."""
    
    def __init__(self, obj):
        """
        Create constants accessor for COM object.
        
        Args:
            obj: COM object with type library information
        """
    
    def __getattr__(self, name):
        """
        Get constant value by name.
        
        Args:
            name (str): Constant name
        
        Returns:
            Constant value
        
        Raises:
            AttributeError: If constant not found
        """

Event Handling

Support for COM events and connection points with automatic event interface discovery.

def GetEvents(obj, sink, interface=None):
    """
    Set up COM event handling with connection points.
    
    Args:
        obj: COM object that fires events
        sink: Event handler object with methods matching event signatures
        interface (type, optional): Specific event interface (auto-detected if None)
    
    Returns:
        Connection point cookie for later disconnection
    
    Raises:
        COMError: If object doesn't support events or connection fails
    """

def ShowEvents(obj, interface=None):
    """
    Display available events for debugging and development.
    
    Args:
        obj: COM object
        interface (type, optional): Specific event interface
    
    Prints event interface information to console
    """

def PumpEvents(timeout):
    """
    Process pending COM events.
    
    Args:
        timeout (float): Maximum time to process events (seconds)
    
    Returns:
        None
    """

Dynamic Dispatch

Late-bound COM object access through IDispatch interface with attribute-style syntax.

class Dispatch:
    """Dynamic dispatch wrapper for late-bound COM object access."""
    
    def __init__(self, obj):
        """
        Create dynamic wrapper for COM object.
        
        Args:
            obj: COM object implementing IDispatch
        """
    
    def __getattr__(self, name):
        """
        Get property or method by name.
        
        Args:
            name (str): Property or method name
        
        Returns:
            Property value or callable method wrapper
        """
    
    def __setattr__(self, name, value):
        """
        Set property value by name.
        
        Args:
            name (str): Property name
            value: New property value
        """
    
    def __call__(self, *args, **kwargs):
        """
        Invoke default method if object is callable.
        
        Args:
            *args: Method arguments
            **kwargs: Named method arguments
        
        Returns:
            Method result
        """

Parameter Wrapping

Utilities for handling output parameters and reference parameters in COM method calls.

def wrap_outparam(obj):
    """
    Wrap object for use as output parameter.
    
    Args:
        obj: Object to wrap
    
    Returns:
        Wrapped object suitable for output parameter
    """

Usage Examples

Basic Object Creation

import comtypes.client

# Create Excel application
excel = comtypes.client.CreateObject("Excel.Application")
excel.Visible = True

# Create Word application with dynamic dispatch
word = comtypes.client.CreateObject("Word.Application", dynamic=True)
word.Visible = True

# Get active Excel instance if available
try:
    active_excel = comtypes.client.GetActiveObject("Excel.Application")
    print("Found active Excel instance")
except comtypes.COMError:
    print("No active Excel instance")

Working with Type Libraries

import comtypes.client

# Generate wrapper module for Excel type library
xl = comtypes.client.GetModule("Excel.Application")

# Access Excel constants
print(xl.xlWorksheet)  # Worksheet type constant
print(xl.xlChart)      # Chart type constant

# Create strongly-typed Excel application
app = comtypes.client.CreateObject("Excel.Application", interface=xl.Application)

Event Handling

import comtypes.client

class ExcelEvents:
    """Event handler for Excel application events."""
    
    def OnWorkbookOpen(self, workbook):
        print(f"Workbook opened: {workbook.Name}")
    
    def OnWorkbookBeforeClose(self, workbook, cancel):
        print(f"Workbook closing: {workbook.Name}")

# Create Excel and set up events
excel = comtypes.client.CreateObject("Excel.Application")
handler = ExcelEvents()

# Connect event handler
connection = comtypes.client.GetEvents(excel, handler)

# Excel will now fire events to our handler
excel.Visible = True
wb = excel.Workbooks.Add()

Dynamic vs Static Binding

import comtypes.client

# Static binding - strongly typed, faster, IntelliSense support
excel_static = comtypes.client.CreateObject("Excel.Application")
excel_static.Visible = True
workbook = excel_static.Workbooks.Add()  # Strongly typed

# Dynamic binding - flexible, slower, runtime resolution
excel_dynamic = comtypes.client.CreateObject("Excel.Application", dynamic=True)
excel_dynamic.Visible = True
workbook = excel_dynamic.Workbooks.Add()  # Dynamic dispatch

Working with Remote Objects

import comtypes.client

# Create object on remote machine
remote_excel = comtypes.client.CreateObject(
    "Excel.Application",
    machine="remote-server.domain.com"
)
remote_excel.Visible = True

Interface Wrapping

import comtypes.client

# Get best interface for object
com_obj = some_com_object  # Raw COM object
wrapped = comtypes.client.wrap(com_obj)  # Get best wrapper

# Manual interface specification
specific_interface = comtypes.client.GetBestInterface(com_obj)

Constants Access

import comtypes.client

# Get Office constants
office = comtypes.client.GetModule("Microsoft Office 16.0 Object Library")
constants = comtypes.client.Constants(office)

# Access constants
print(constants.msoShapeRectangle)
print(constants.msoTextOrientationHorizontal)

# Or access directly from module
print(office.msoShapeRectangle)

Install with Tessl CLI

npx tessl i tessl/pypi-comtypes

docs

automation.md

client-api.md

core-com.md

index.md

server.md

utilities.md

tile.json