1

我使用以下命令启动了 Libre-Office Calc:

$ 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")

然后我称之为:

myUno = UnoStruct()
BEGIN: constructor
END: constructor

并尝试得到它

active_sheet = myUno.model.CurrentController.ActiveSheet

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

似乎modelNone(空)

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

那么在构造函数中发生了什么?它不应该还在吗?我试图避免使用样板代码。

4

2 回答 2

2

我将添加到您声明localContext = None, resolver = None, etc.为类变量的 Barros 的答案中。所以修改后的代码是这样的(如果你需要所有这些变量作为实例变量):

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()
于 2017-07-26T16:18:11.200 回答
2

你需要明确

   self.model = desktop.getCurrentComponent()

内部的model变量是该方法的本地变量,除非您分配它,否则__init__不会附加到实例。self

当您model在类下定义时,但在__init__您定义的方法之外 a class attribute,它将在该类的所有实例中。

没有它,当您访问时,myUno.model您将面临一个AttributeError.

于 2017-07-26T16:13:53.467 回答