Fixing – Cannot change thread mode after it is set
Life is hard when you don’t understand all this Windows com stuff. Well life with Windows and Python is hard at least.
Here’s one of the weirdest errors I ever got and how at least I was able to fix it.
My code just started raising this error one day:
‘Cannot change thread mode after it is set.’
(I believe it had this number associated with the error: -2147417850)
The weirdest thing is the the error was raised from whatever statement followed the Pythoncom dispatch thing:
self._qbxmlrp = win32com.client.DispatchEx("QbXMLRP2e.RequestProcessor")
Even if the statement was something mundane like print 'hi'.
I’ve found the only way to debug this sort of thing when there’s no help to be found on the internet is to create what I call a mimimum failing example. Make a seperate copy of your code and tear things out until it starts working again.
Following this process I saw that my code only raised this error when another module (a little feller’ to talk to SQL Server) called the following function more than once (just once was ok though):
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
The first solution I tried was calling pythoncom.CoUninitialize() after every time pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) was called. I don’t know what I’m doing but the names make it sound like the right thing to do, right?
But that didn’t work. So I ended up refactoring the module using a singleton type of deal so that pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) is only called once.
That fixed the issue, though it’s quite a hollow victory since I still don’t know what’s going on. This must be how the guy in the Chinese room feels.
Update:
After a second look, all that was required was to stop using this code I’ve previously posted on here. Are you using anything like that, dealing file I/O or STOUT?
I can’t image why that would have helped but it does.