我的工作流程通常遵循以下链:
使用soffice命令在libreoffice中打开示例数据文件,以便可以连接示例数据文件,这是一个控制台命令:
$ soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" /path/to/sample/data.ods
运行python控制台并键入以下连接命令:
>>> sys.path.append("/path/to/uno_lib/.local/lib/python3")
>>> import uno
>>> local_context = uno.getComponentContext()
>>> resolver = local_context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local_context)
>>> ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
>>> smgr = ctx.ServiceManager
>>> desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
>>> document = desktop.getCurrentComponent()
使用uno命令提取数据
pseudo-code >>> document.getSheet("data").getCellRange("B5", "H15")
显然,我想把所有这些都放到一个文件“connect”和函数“connection”中,比如:
连接.py
import os
import uno
def connection():
os.system(soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" /path/to/sample/data.ods)
context ...
resolver
ctx ...
smgr ....
desktop ...
document ...
return document
所以我可以简单地说:
$ python
>>> import connect
>>> document = connection()
>>> document.getSheet("DataSheet").getCellRange("B5", "H15")
哦,我多么喜欢这个:)
问题:当我调用函数“connection()”时,控制台在打开计算文件的系统命令处暂停,只有当我关闭计算文件时,脚本才会继续,但随后它就不再连接了,因为文件已关闭:(我如何才能避免这种情况?
1条答案
按热度按时间d8tt03nd1#
首选的方法是使用shell脚本而不是系统调用来启动libreoffice。
下面是我使用的shell脚本:
否则,您将需要线程和sleep命令从python内部与操作系统交互。这比直接启动lo更困难、更不可靠。