pythonpython-3.xlibreofficelibreoffice-calclibreoffice-macros

Python 3 class returns null when using contructor


I started Libre-Office Calc with the following command:

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

import uno

# Class so I don't have to do this crap over and over again...
class UnoStruct():
    localContext = None
    resolver = None
    ctx = None
    smgr = None
    desktop = None
    model = None
    def __init__(self ):
        print("BEGIN: constructor")
        # get the uno component context from the PyUNO runtime
        localContext = uno.getComponentContext()

        # create the UnoUrlResolver
        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

        # get the central desktop object
        desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

        # access the current writer document
        model = desktop.getCurrentComponent()

        print("END: constructor")

And then I call it with:

myUno = UnoStruct()
BEGIN: constructor
END: constructor

And attempt to get it with

active_sheet = myUno.model.CurrentController.ActiveSheet

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

and it appears that the model is None (null)

>>> active_sheet = myUno.model
>>> print( myUno.model )
None
>>> print( myUno )
<__main__.UnoStruct object at 0x7faea8e06748>

So what happened to it in the constructor? Shouldn't it still be there? I'm trying to avoid the boiler plate code.


Solution

  • I would add to the answer of Barros that you declare localContext = None, resolver = None, etc. as class variables. So the modified code is this (if you need all these variables as instance variables):

    class UnoStruct():
        def __init__(self ):
            # get the uno component context from the PyUNO runtime
            self.localContext = uno.getComponentContext()
    
            # create the UnoUrlResolver
            self.resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
    
            # connect to the running office
            self.ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
            self.smgr = ctx.ServiceManager
    
            # get the central desktop object
            self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    
            # access the current writer document
            self.model = desktop.getCurrentComponent()