Попытка оживить образец сценария PyUNO под названием Wavelet, чтобы узнать, как работает LO в настоящее время, и начать заново. Поскольку LibreOffice и UNO немного изменились со времени создания сценария, у меня возникают проблемы.
Удалось получить объект рабочего стола. Теперь я хочу получить компонент открытого документа. Как мне добиться этого правильно? Вызов desktop.getCurrentComponent() возвращает None.
Версия LibreOffice: 6.4.6.2.
Система: Ubuntu MATE 20.04 x86_64.
Код следующий:
#!/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( () )
Выход:
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'
Кросс размещен по следующему адресу: https://ask.libreoffice.org/en/question/283785/why-does-desktopgetcurrentcomponent-return-none-in-pyuno/






Попробуйте не указывать desktop.getCurrentComponent() переменную, поэтому сотрите doc =. Я помню, у меня была такая проблема, но я не понимал, почему она это делает. Все, что я помню, это то, что отсутствие имени заставило мой код работать. Это единственный совет, который я могу вам дать.
Пытался дождаться, пока компонент документа станет доступным. И это сработало:
doc = None
while doc is None:
doc = desktop.getCurrentComponent()
Спасибо за ваш ответ! К сожалению, это не работает:
Traceback (most recent call last):File "./wavelet.py", line 62, in <module>wavelet.trigger( () )File "./wavelet.py", line 24, in triggersearch = desktop.getCurrentComponent().createSearchDescriptor()AttributeError: 'NoneType' object has no attribute 'createSearchDescriptor'Возможно, мы только что нашли ошибку.