pythoncom.CoInitialize()
COM initialization; it goes on the first line of the script. Any thread that touches COM has to call it again, or you get "CoInitialize has not been called". Pair it
Signature
Notes
pythoncom.CoUninitialize() at the end.Python example (runnable)
pywin32. The example assumes app / doc / page / layer are already connected.
See Connection & Initimport pythoncom # low-level COM module from pywin32
# Start COM for this thread. Required once before any COM call on Windows
pythoncom.CoInitialize()
# Release it when the script ends (keep this habit, always pair the two)
# pythoncom.CoUninitialize()
print("COM is ready")
What this line is for
COM has one hard rule: a thread must declare which apartment it belongs to before it touches COM.
pythoncom.CoInitialize() does exactly that — it marks the calling thread as STA
(single-threaded apartment).
Why STA matters here: CorelDRAW is an application with a window, a message pump, and UI state. Objects like that have to be pinned to one thread; cross-thread access goes through marshalling, otherwise window messages and internal state get scrambled. It is an STA object, not something any random thread can call into.
What happens if you skip it
The usual text:
pythoncom.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
That is HRESULT 0x800401F0 (CO_E_NOTINITIALIZED).
It is not necessarily raised on the line that creates the object. Dispatch hands back a
dynamic proxy, and only actual calls travel through COM. So the symptom is often "the first few
lines ran fine, line 8 blew up" — which makes people blame the method on line 8 instead of the
missing initialisation several lines earlier.
Why it sometimes works on the main thread without it
Three reasons, all coincidence, none of them a contract:
- Some GUI framework initialised COM for the main thread at startup (Tk, certain wx setups, the interactive pane of some IDEs).
- Something else in the import chain initialised it —
win32com.shelland friends. - You were in an interactive session where it had already been initialised once and the state was still there.
So the many tutorial snippets that omit CoInitialize are not wrong, they simply never
hit a situation that requires it. Change the thread, move to a service context, run it from Task
Scheduler — and it fails immediately.
Return value: S_OK versus S_FALSE
S_OK(0) means this call did the initialisation. S_FALSE(1) means the thread
was already initialised in the same apartment and this call only incremented the count. Either way
COM is usable, and either way the matching CoUninitialize is owed.
In practice a short-lived script can skip the teardown — COM cleans up when the process exits. A long-running process that creates and destroys threads (a service, a plugin host) must pair the calls, otherwise the count leaks and resources are not released when threads die.
Worker threads always need it
Apartment state is per-thread, not per-process. Every worker in a ThreadPoolExecutor
needs its own call:
import threading, pythoncom
_local = threading.local()
def ensure_com():
if getattr(_local, "ready", False):
return
pythoncom.CoInitialize() # once per thread
_local.ready = True
The more important rule, though: do not share one app object across threads.
CorelDRAW is STA. A proxy obtained on the main thread and used from an MTA thread forces COM to
marshal, and pywin32's dynamic proxy has no message pump behind it. The usual outcomes are
RPC_E_WRONG_THREAD (0x8001010E) or a call that simply hangs.
CorelDRAW is also a single-instance application, so concurrent access buys you nothing. The structure that works: one thread drives CorelDRAW serially, other threads do file IO and data work, with a queue in between.
CoInitialize versus CoInitializeEx
pythoncom.CoInitialize() is the STA form. For MTA you need
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED).
Initialise a thread one way and then the other and you get 0x80010106
(RPC_E_CHANGED_MODE). That error almost always means "the framework already initialised this
process as MTA and then I called CoInitialize() on top". Do not go looking at CorelDRAW when you
see it — find out who initialised first.
A complete version
import pythoncom
import win32com.client
def connect(progid="CorelDRAW.Application"):
pythoncom.CoInitialize()
try:
app = win32com.client.Dispatch(progid)
app.Visible = True
return app
except pythoncom.com_error as e:
hr = e.args[0]
if hr == -2147221008:
raise SystemExit("COM not initialised: check CoInitialize on this thread")
if hr == -2147221005:
raise SystemExit("Invalid ProgID: check the version suffix or read CurVer")
if hr == -2147221164:
raise SystemExit("Class not registered: bitness mismatch is the usual cause")
raise
app = connect()
print("CorelDRAW", app.Version)
When you can leave it out
Single-threaded, one-shot, interactive desktop scripts usually survive without it. Write it explicitly whenever any of these is true: multiple threads, running as a service or scheduled task, loaded by a host process (VBA calling Python, some RPA tools), or code you will hand to someone else.
The cost of the line is one line. The cost of omitting it is a failure on somebody else's machine months later, with an error message that points at the wrong place.
About this section: Connection & Init
Connection & Init — connecting to CorelDRAW over COM.
- This section has 8 entries; this is one of them.
- See the full section index: Connection & Init
Other entries in this section
- win32com.client.Dispatch("CorelDRAW.Application.21")Connect by version number; 21 is CorelDRAW 2019. If CDR is already run
- app.Visible = TrueShows the CDR window. Setting it False is faster for batch runs, but k
- win32com.client.Dispatch("CorelDRAW.Application")No version number, so it binds to whatever version is registered as de
- win32com.client.GetActiveObject("CorelDRAW.Application.21")Attaches to an instance that is already open and never starts a new pr
- win32com.client.gencache.EnsureDispatch(progid)Once the constant cache exists you can write cdrTextShape instead of 6
- app.VersionReturns the version as a string. Use it to confirm which version you a
- app.Quit()Closes CorelDRAW entirely. Don't call it at the end of a batch job — i