UNO: choosing between running office instances

When I start office as

soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

I can then choose File → Open…, and open a document in a completely new window. The code I know and have found everywhere, which is:

#!python
import uno

# run libreoffice as:
# soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

def connectToLo():
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localContext )
    # connect to the running office
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    return desktop.getCurrentComponent()

model = connectToLo()

returns a descriptor of the currently focused instance, whichever it is. But in my current task I need to open 2 windows (Calc and Impress), and work with them simultaneously. How do I do that?

I hope nobody minds I answer my question: after twiddling a bit with Python interactive prompt I figured I can iterate over desktop.Components variable (as opposed to using desktop.CurrentComponent that is the focused window), and figure out which instance it is e.g. by using a title of each “component”.

Here’s an example code that iterates over windows of the LO instance and prints their titles:

#!python
import uno

# run libreoffice as:
# soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

def connectToLO():
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localContext )
    # connect to the running office
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    return desktop

desktop = connectToLO()
for c in desktop.Components:
    print(c.Title)

Example output:

$ python print-lo-instances-titles.py
SML_sample for Kotya.pptx
Untitled 1

Hi

my profile content may be of interest for your Python efforts

LibreOfficiant