Why does desktop.getCurrentComponent() return None in PyUNO?

Trying to revive a PyUNO sample script called Wavelet to learn how LO works nowadays and get re-started. Since LibreOffice & UNO changed a bit from the script’s creation time I am running into problems.

Managed to get the desktop object. Now I want to retrieve the open document’s component. How do I achieve this properly? The desktop.getCurrentComponent() call returns None.

LibreOffice version: 6.4.6.2.

System: Ubuntu MATE 20.04 x86_64.

The code follows:

#!/usr/bin/python3

def TestWave(event):
    wavelet = Wavelet(XSCRIPTCONTEXT)
    wavelet.trigger( () )

import uno
import unohelper
import string
from com.sun.star.task import XJobExecutor

class Wavelet( unohelper.Base, XJobExecutor ):
    def __init__( self, ctx ):
        self.ctx = ctx

    def trigger( self, args ):
        desktop = self.ctx.ServiceManager.createInstanceWithContext(
            "com.sun.star.frame.Desktop", self.ctx )

        doc = desktop.getCurrentComponent()
        print('doc:', doc)

        #try:
        search = doc.createSearchDescriptor()
        search.SearchRegularExpression = True
        search.SearchString = "\\<(k|s|v|z|o|u|i|a) "

        found = doc.findFirst( search )
        while found:
            print("found:", found.String)
            found.String = string.replace( found.String, " ", u"\xa0" )
            found = doc.findNext( found.End, search)

        #except:
        #    pass


g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
        Wavelet,
        "name.vojta.openoffice.Wavelet",
        ("com.sun.star.task.Job",),)

if __name__ == "__main__":
    import os
    # Start OpenOffice.org, listen for connections and open testing document
    os.system( "loffice '--accept=socket,host=localhost,port=2002;urp;' --writer ./WaveletTest.odt &" )
    # Get local context info
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
      "com.sun.star.bridge.UnoUrlResolver", localContext )
    ctx = None
    # Wait until the OO.o starts and connection is established
    while ctx == None:
      try:
        ctx = resolver.resolve(
          "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
      except:
        pass
    # Trigger our job
    wavelet = Wavelet( ctx )
    wavelet.trigger( () )

Output:

doc: None
Traceback (most recent call last):
  File "./wavelet.py", line 62, in <module>
    wavelet.trigger( () )
  File "./wavelet.py", line 24, in trigger
    search = doc.createSearchDescriptor()
AttributeError: 'NoneType' object has no attribute 'createSearchDescriptor'

Cross posted at the following address: python - Why does desktop.getCurrentComponent() return None in PyUNO? - Stack Overflow.

Hello,

Although not into Writer & using the search functions, had no problem running this with my own search.
Only problem was that this is not valid string.replace. But after commenting out all ran fine. Could find word(s) or multiple instances of letters.

Yes, I can confirm that string.replace(…) is not valid.

Hello,

Should have checked this before. You get an error when the code is run and the document (WaveletTest.odt) is not open.

Error I get is:

AttributeError: 'NoneType' object has no attribute 'createSearchDescriptor'

Open the document and the code executes as I mentioned in my comment.

Results document open (my test):

found: l
found: l
found: l

Process finished with exit code 0

Inspired by the answer by @Ratslinger, tried to wait for the document component to become available. And it worked:

    doc = None
    while doc is None:
        doc = desktop.getCurrentComponent()