0

I created a project that displays a Windows toast notification using the 'winrt' module. When I run my code in PyCharm, the script executes normally until completion. After compiling using PyInstaller and running the generated exe, I get an error for one of the 'winrt' imports:

Traceback (most recent call last):
  File "notification.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "message.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "winrt\__init__.py", line 4, in <module>
RuntimeError: Cannot change thread mode after it is set.
[9720] Failed to execute script 'notification' due to unhandled exception!

My imports for 'winrt' are:

import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom

If anyone one knows why I get this error, I would appreciate any help!

2
  • This is RCP_E_CHANGED_MODE error. A very classical COM/WinRT error that happens if some code calls CoInitialize/CoInitializeEx/RoInitialize in a thread while another piece of code has called it already with different parameters (STA vs MTA). Difficult to diagnose the error lies somewhere in the libraries you use or in the order you call them. Note you often can catch this error and just continue. Commented Sep 27, 2021 at 6:12
  • 1
    I had this same problem, and the error can't be caught because it happens on import (in a library doing some fancy importlib stuff I couldn't replicate on the receiving side). However, (1) it seemed to only be a problem in the VSC debugger, and (2) even there, it went away if I just commented out their _winrt.init_apartment() line. Commented Aug 29, 2022 at 15:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.