最后,我有一个可行的解决方案。叮!东!在#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.uno import Exception
from com.sun.star.lang import IllegalArgumentException
def test2(*args):
localContext = uno.getComponentContext()
localsmgr = localContext.ServiceManager
resolver = localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except NoConnectException as e:
print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
return
msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript('vnd.sun.star.script:fs2TimeStamp.py$fs2_TimeStamp?language=Python&location=user')
try:
scriptx.invoke((), (), ())
except IllegalArgumentException as e:
print ("The command given is invalid ( "+ e.Message+ ")")
return
except RuntimeException as e:
print("An unknown error occurred: " + e.Message)
return
except Exception as e:
print ("Script error ( "+ e.Message+ ")")
return(None)
test2()
注意:为了清楚起见,现有的python脚本称为fs2TimeStamp.py,它包含1(一)个定义为def fs2_TimeStamp(*args):
请参阅以下行:
^{pr2}$
它存储在$HOME/.config/libreoffice/4/user/Scripts/python
要使此解决方案工作,libreoffice必须在监听模式下运行,因此使用如下命令启动libreoffice:soffice " accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" writer norestore
或者nohup soffice " accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" writer norestore &
或者,您可以使用更直接的方法(对于本例中的writer):lowriter " accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp"
或者nohup lowriter " accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp" &
还要注意您必须用python3运行脚本