I would like to use the Python win32com library (part of pywin32) to receive events from the local OneNote Application Interface (as documented here). Note this question does NOT relate to the newer online "REST" OneNote interface, but rather to the older COM-based local desktop interface.
When I try to use this simple example:
import time, pythoncom, win32com.client as COM
class OneNoteEvents:
def OnHierarchyChange(self, PageID=pythoncom.Empty):
print('Hierarchy has changed!!')
onevt = COM.DispatchWithEvents('OneNote.Application', OneNoteEvents)
while True:
pythoncom.PumpWaitingMessages() # Non-blocking
time.sleep(0.02)
I get the following error (some identifying file path elements redacted):
Traceback (most recent call last):
File "C:\...\OneNote_event_compact.py", line 7, in <module>
onevt = COM.DispatchWithEvents('OneNote.Application', OneNoteEvents)
File "C:\Users\<XXXX>\AppData\Local\Programs\Python\Python313\Lib\site-packages\win32com\client\__init__.py", line 346, in DispatchWithEvents
events_class.__init__(instance, instance)
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
File "C:\Users\<XXXX>\AppData\Local\Temp\gen_py\3.13\0EA692EE-BB50-4E3C-AEF0-356D91732725x0x1x1.py", line 290, in __init__
cookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy))
pywintypes.com_error: (-2147467259, 'Unspecified error', None, None)
What I know so far:
- The error occurs in code generated by win32com in the 'gen_py' folder, when the Advise() call is made.
- I can otherwise use the non-event aspects of the OneNote COM interface perfectly well from Python, to retrieve the page hierarchy, etc.
- I can also make a simple Event example for Excel, which also works perfectly well, and prints messages as the cursor moves around the sheet:
import time, pythoncom, win32com.client as COM
class ExcelEvents:
def OnSheetSelectionChange(self, sh=None, Target=None):
print(f'Selection Changed {sh.Name} {app.ActiveCell.Address}')
app = COM.DispatchWithEvents("Excel.Application", ExcelEvents)
app.Visible=True
while True: pythoncom.PumpWaitingMessages(); time.sleep(0.05)
The problem seems specific to the OneNote Application Event interface, causing a failure at the Advise() call for reasons I don't fully understand. Any hints for work-arounds, or approaches to determine the cause would be greatly appreciated.