如何在LibreOffice Python脚本中持久化对象以复用串口连接?
LibreOffice Python 串口对象持久化问题
我编写了一个使用串行IO的LibreOffice Python脚本,在我的系统中打开串口的过程非常缓慢(约1秒),因此希望保持串口处于打开状态,仅在需要时发送数据。但LibreOffice Python似乎每次调用都会重新加载Python框架,和常规Python不同——常规Python里进程是持久化的,模块中的非封装代码仅在导入时运行一次。请问有没有办法在LibreOffice Python的多次调用间持久化对象?
附当前测试代码:
SerialObject=None def return_global(): return str(SerialObject) # 总是返回"None" def init_serial_object(): SerialObject=True
解决方法
1. 使用 LibreOffice 全局脚本上下文存储对象
LibreOffice 提供的XSCRIPTCONTEXT和全局服务容器可以实现跨调用的数据共享,你可以将串口对象存储到全局设置中:
修改后的示例代码:
import uno def init_serial_object(): ctx = uno.getComponentContext() smgr = ctx.getServiceManager() # 获取全局宏设置容器 global_settings = smgr.createInstanceWithContext("com.sun.star.document.MacroGlobalSettings", ctx) # 存储串口对象(此处用True替代实际的串口实例) global_settings.setMacroSetting("SerialObject", True) def return_global(): ctx = uno.getComponentContext() smgr = ctx.getServiceManager() global_settings = smgr.createInstanceWithContext("com.sun.star.document.MacroGlobalSettings", ctx) # 读取存储的对象 serial_obj = global_settings.getMacroSetting("SerialObject") return str(serial_obj) if serial_obj is not None else "None"
2. 绑定文档存储对象(针对特定文档的脚本)
如果脚本只和某个LibreOffice文档关联,可以将串口对象存入文档的自定义属性:
def init_serial_object(): doc = XSCRIPTCONTEXT.getDocument() props = doc.getDocumentProperties() custom_props = props.getUserDefinedProperties() # 不存在则添加属性 if not custom_props.hasByName("SerialObject"): custom_props.addProperty("SerialObject", 0, True) custom_props.setPropertyValue("SerialObject", True) def return_global(): doc = XSCRIPTCONTEXT.getDocument() props = doc.getDocumentProperties() custom_props = props.getUserDefinedProperties() if custom_props.hasByName("SerialObject"): return str(custom_props.getPropertyValue("SerialObject")) else: return "None"
3. 关键注意事项
- 不用串口时务必手动关闭,避免资源占用泄漏。
- 全局存储的对象要考虑线程安全,LibreOffice宏环境可能存在多线程调用场景。
- LibreOffice重启后,存储的对象会被清除,需要重新初始化。
内容的提问来源于stack exchange,提问作者david
相关产品推荐
相关产品推荐

