Pure Python COM package for Windows COM automation and interoperability
npx @tessl/cli install tessl/pypi-comtypes@1.4.00
# comtypes
1
2
A pure Python COM (Component Object Model) package for Windows that enables Python applications to interact with COM objects, servers, and interfaces. Built on top of Python's ctypes foreign function interface, comtypes provides comprehensive COM functionality with zero additional dependencies, supporting both early-bound (strongly-typed) and late-bound (dispatch-based) programming models.
3
4
## Package Information
5
6
- **Package Name**: comtypes
7
- **Language**: Python
8
- **Platform**: Windows (COM technology specific)
9
- **Installation**: `pip install comtypes`
10
11
## Core Imports
12
13
```python
14
import comtypes
15
```
16
17
For high-level COM automation:
18
19
```python
20
from comtypes.client import CreateObject, GetActiveObject, GetEvents
21
```
22
23
For automation types and interfaces:
24
25
```python
26
from comtypes.automation import VARIANT, IDispatch
27
```
28
29
For server development:
30
31
```python
32
from comtypes.server import IClassFactory
33
```
34
35
## Basic Usage
36
37
```python
38
import comtypes.client
39
40
# Create a COM object (e.g., Excel application)
41
xl = comtypes.client.CreateObject("Excel.Application")
42
xl.Visible = True
43
44
# Create a new workbook
45
wb = xl.Workbooks.Add()
46
ws = wb.ActiveSheet
47
48
# Write data to cells
49
ws.Cells(1, 1).Value = "Hello"
50
ws.Cells(1, 2).Value = "World"
51
52
# Save and close
53
wb.SaveAs("C:\\temp\\example.xlsx")
54
wb.Close()
55
xl.Quit()
56
```
57
58
```python
59
# Using dispatch for late binding
60
import comtypes.client
61
62
# Create object with dynamic dispatch
63
word = comtypes.client.CreateObject("Word.Application", dynamic=True)
64
word.Visible = True
65
66
# Create new document
67
doc = word.Documents.Add()
68
doc.Content.Text = "Hello from Python!"
69
70
# Close without saving
71
doc.Close(SaveChanges=False)
72
word.Quit()
73
```
74
75
## Architecture
76
77
comtypes implements a comprehensive COM infrastructure with several key components:
78
79
- **COM Initialization**: Automatic COM apartment initialization with configurable threading models
80
- **Object Creation**: Multiple pathways for creating and accessing COM objects (ProgID, CLSID, moniker, active objects)
81
- **Interface Management**: Type-safe interface definitions with automatic QueryInterface support
82
- **Type Library Integration**: Automatic Python wrapper generation from COM type libraries
83
- **Event Handling**: Connection point support for COM events and callbacks
84
- **Server Support**: Framework for implementing COM servers in Python
85
- **Error Handling**: Comprehensive HRESULT error code management and exception mapping
86
87
## Capabilities
88
89
### Core COM Functionality
90
91
Essential COM operations including object creation, interface management, apartment initialization, and GUID handling. Provides the foundation for all COM interactions.
92
93
```python { .api }
94
def CoCreateInstance(clsid, interface=None, clsctx=None, machine=None): ...
95
def CoGetObject(displayname, interface=None): ...
96
def CoInitializeEx(flags=None): ...
97
def CoUninitialize(): ...
98
class GUID: ...
99
class IUnknown: ...
100
```
101
102
[Core COM](./core-com.md)
103
104
### Client API
105
106
High-level functions for consuming COM objects and services. Includes object creation, type library processing, event handling, and dynamic dispatch support.
107
108
```python { .api }
109
def CreateObject(progid, clsctx=None, machine=None, interface=None, dynamic=False): ...
110
def GetActiveObject(progid, interface=None, dynamic=False): ...
111
def GetEvents(obj, sink, interface=None): ...
112
def GetModule(tlib): ...
113
class Constants: ...
114
```
115
116
[Client API](./client-api.md)
117
118
### Automation and IDispatch
119
120
COM automation support with VARIANT handling, dispatch interfaces, and type conversion. Enables interaction with automation servers like Microsoft Office applications.
121
122
```python { .api }
123
class IDispatch: ...
124
class VARIANT: ...
125
def BSTR(value): ...
126
# VARIANT type constants
127
VT_EMPTY: int
128
VT_BSTR: int
129
VT_DISPATCH: int
130
```
131
132
[Automation](./automation.md)
133
134
### Server Development
135
136
Framework for implementing COM servers in Python, including class factories, registration utilities, and connection point support for events.
137
138
```python { .api }
139
class IClassFactory: ...
140
def RegisterActiveObject(comobj, weak=True): ...
141
class COMObject: ...
142
class CoClass: ...
143
```
144
145
[Server Development](./server.md)
146
147
### Utilities and Support
148
149
Helper functions, type conversion utilities, SafeArray support, and specialized interfaces for persistence, shell integration, and type library processing.
150
151
```python { .api }
152
def byref_at(obj, offset): ...
153
def _midlSAFEARRAY(itemtype): ...
154
class IPersist: ...
155
class IShellLinkW: ...
156
```
157
158
[Utilities](./utilities.md)
159
160
## Types
161
162
### Core Types
163
164
```python { .api }
165
class GUID:
166
"""Globally unique identifier for COM interfaces and classes."""
167
def __init__(self, name: str = None): ...
168
def __str__(self) -> str: ...
169
def __eq__(self, other) -> bool: ...
170
@classmethod
171
def from_progid(cls, progid: str) -> 'GUID': ...
172
@classmethod
173
def create_new(cls) -> 'GUID': ...
174
def as_progid(self) -> str: ...
175
176
class COMError(Exception):
177
"""Exception raised for COM operation failures."""
178
def __init__(self, hresult: int, text: str = None, details: tuple = None): ...
179
180
class ReturnHRESULT(Exception):
181
"""Exception for returning HRESULT codes from COM method implementations."""
182
def __init__(self, hresult: int, text: str = None): ...
183
```
184
185
### COM Context Constants
186
187
```python { .api }
188
CLSCTX_INPROC_SERVER: int # 1
189
CLSCTX_INPROC_HANDLER: int # 2
190
CLSCTX_LOCAL_SERVER: int # 4
191
CLSCTX_REMOTE_SERVER: int # 16
192
CLSCTX_INPROC: int # 3
193
CLSCTX_SERVER: int # 5
194
CLSCTX_ALL: int # 7
195
```
196
197
### COM Initialization Constants
198
199
```python { .api }
200
COINIT_APARTMENTTHREADED: int # 2
201
COINIT_MULTITHREADED: int # 0
202
COINIT_DISABLE_OLE1DDE: int # 4
203
COINIT_SPEED_OVER_MEMORY: int # 8
204
```