import win32com.client as win32
excel = win32.gencache.EnsureDispatch(\'Excel.Application\')
for wb in excel.Workbooks:
print(wb.Name)
When I
The reason must be that in one case, you connect to a running Excel instance while in the other one, open a new one (or connect to some other one).
To ensure connecting to an existing instance, you can use win32com.client.GetActiveObject(<ProgID>)
as per Attaching to an already running Office application from your application using GetActiveObject or BindToMoniker – .NET4Office.
I'm not completely sure when either happens, but these are the patterns I noticed that may explain what you see:
excel.exe
instance is spawned by the svchost.exe
process hosting the DCOM process launcher service
So if you e.g. run your code from interactive console, or the IDE doesn't restart the Python process each time (unlikely but possible), you may have old existing references.