I am trying to build an app that will connect into the API of another running app on Windows through the com interface. This has been successfully done using Jupyter and win32com. No issues have been experienced connecting in and re-running the cell multiple times.
However, when attempting the same in Streamlit, I am able to get it working for about 30 secs. After that and when the app is updated or rerun it results in a com_error.
I have recreated the issue using Excel and the same behavior is experienced, which rules out the application I am trying to build this for.
The code I am using is an adapted version of this SO post:
Python Multithreading COM Objects - Stack Overflow
Any help or suggestions on this would be appreciated. Thanks
Steps to reproduce
This simple code creates a new Workbook in Excel each time the button is pressed.
import streamlit as st import win32com.client import pythoncom st.header('Test') com = win32com.client.Dispatch("Excel.Application") com_id = win32com.client.pythoncom.CoMarshalInterThreadInterfaceInStream( win32com.client.pythoncom.IID_IDispatch, com) pythoncom.CoInitialize() api = win32com.client.Dispatch(pythoncom.CoGetInterfaceAndReleaseStream(com_id, pythoncom.IID_IDispatch)) add_sheet = st.button('Add Worksheet') if add_sheet: api.Workbooks.Add()
No error to occur when the app is rerun after 30 seconds and the communication with the active app to be maintained.
When the app is run, I am able to click the Add Workbook button multiple times. This generates a new instance of Excel and a clean workbook.
However, after about 30 secs, when the button is pressed it results in a com_error:
com_error: (-2147221008, ‘CoInitialize has not been called.’, None, None)
And the following trace:
File "C:\Users\Andy\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 562, in _run_script exec(code, module.__dict__) File "C:\PythonProjects\streamlit_integration\test_app.py", line 7, in <module> com = win32com.client.Dispatch("Excel.Application") File "C:\Users\Andy\AppData\Roaming\Python\Python39\site-packages\win32com\client\__init__.py", line 117, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx) File "C:\Users\Andy\AppData\Roaming\Python\Python39\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Users\Andy\AppData\Roaming\Python\Python39\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(
- Streamlit version: 1.13.0
- Python version: 3.9.13 64 bit
- Using Conda? PipEnv? PyEnv? Pex? None
- OS version: Win 10
- Browser version: Edge 108.0.1462.76