导入 Python 模块

LibreOffice Python 脚本有三种不同的分类, 分别为「个人」「共享」或「文档内嵌」。它们存储在 Python 脚本组织与位置 中描述的不同位置。要导入 Python 模块, 模块必须位于 Python 运行时已知的位置。

针对基于文件系统的模块与基于文档的模块展示该机制。为简明起见, 异常处理已省略。术语「库」与「目录」同义,「脚本」与「模块」同义,会交替使用。「Python 宏」指模块内的函数。

warning

请注意,从 <User Profile>/Scripts/python 运行 Python 宏时, 总会在本地目录 <User Profile>/Scripts/python/pythonpath 中查找。


文件系统模块导入

LibreOffice Basic 库包含类、例行程序与变量,Python 模块包含类、函数与变量。常用的 Python 或 UNO 功能必须存储在「我的宏」,路径为「(用户配置文件目录)/Scripts/python/pythonpath」。Python 库有助于组织模块,避免模块命名冲突。在共享模块中导入「uno.py」。

用户或共享模块

将个人与共享的 Python 脚本的目录包含在 Python 运行时路径中, 就可以导入这些脚本。有关省略的「会话类」的详细信息, 请参阅获取会话信息页面。


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
        import sys
            
        user_lib = Session().UserPythonScripts  # 用户脚本位置
        if not user_lib in sys.path:
            sys.path.insert(0, user_lib)  # 添加到搜索路径
        import screen_io as ui  # 「screen_io.py」模块位于 user_lib 目录
        # 您的代码在此继续
    

此 Python 示例将本地 XSCRIPTCONTEXT 变量暴露给导入的模块:


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
        import uno, sys
            
        share_lib = Session.SharedPythonScripts()  # 共享脚本位置
        if not share_lib in sys.path:
            sys.path.insert(0, share_lib)  # 添加到搜索路径
        from IDE_utils import ScriptContext  # 「IDE_utils.py」位于共享 Python 脚本目录。
        XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
        # 您的代码在此继续
    

为应用程序安装模块

与个人与共享脚本不同, LibreOffice 自带脚本可以随时导入。除 unounohelper LibreOffice Python 模块以外, 位于 <安装路径>/program 目录中的其他脚本可以直接导入, 例如 msgbox 模块。

使用 Python shell:

>>> import msgbox, uno

>>> myBox = msgbox.MsgBox(uno.getComponentContext())

>>> myBox.addButton("okay")

>>> myBox.renderFromButtonSize()

>>> myBox.numberOflines = 2

>>> print(myBox.show("A small message",0,"Dialog title"))

文档模块导入

导入 Python 文档内嵌模块的操作如下图所示。错误处理未详细展示。当文档处于打开状态时,将更新 Python 运行时路径。要了解如何将 Python 宏与文档事件相关联,请参阅《事件驱动的宏》。


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
            
        import sys, uno
            
        def OnDocPostOpenLoadPython():
            """ 文档加载完成后,准备 Python 模块导入 """
            PythonLibraries.loadLibrary('lib/子目录')  # 将目录添加到搜索路径
            PythonLibraries.loadLibrary('my_gui', 'screen_io')  # 添加目录 & 导入 screen_io
            
        def OnDocQueryCloseUnloadPython():
            """ 文档关闭后清理 PYTHON_PATH """
            PythonLibraries.unloadLibrary('my_gui')  # 清理 Python 运行时路径
            # Note: imported modules remain loaded in this example.
            
        class PythonLibraries():
            """ Python 库加载器与模块导入器
            
            引自 Hubert Lambert《函数库》
            位于 https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213 """
            def isImportedModule(module_name: str) -> bool:
                """ 检查运行时模块列表 """
                return (module_name in sys.modules.keys())
            def isLoadedLibrary(lib_name: str) -> bool:
                """ 检查 PYTHON_PATH 内容 """
                return (lib_name in sys.path)
            def loadLibrary(lib_name: str, module_name=None):
                """ 将路径添加到 PYTHON_PATH,导入已命名模块 """
                doc = XSCRIPTCONTEXT.getDocument()
                url = uno.fileUrlToSystemPath(
                    '{}/{}'.format(doc.URL,'Scripts/python/'+lib_name)
                if not url in sys.path:
                    sys.path.insert(0, url)
                if module_name and not module_name in sys.modules.keys():
                    return zipimport.zipimporter(url).load_module(module_name)
            def unloadLibrary(lib_name: str):
                """ 从 PYTHON_PATH 删除目录 """
                sys.path.remove(lib_name)
            
        g_exportedScripts = (OnDocPostOpenLoadPython, OnDocQueryCloseUnloadPython)
    

请支持我们!