Importació de mòduls Python

LibreOffice Python scripts come in three distinct flavors, they can be personal, shared or embedded in documents. They are stored in varying places described in Python Scripts Organization and Location. In order to import Python modules, their locations must be known from Python at run time.

This mechanism is illustrated for file system based modules and document based modules. Exception handling is omitted for clarity. The terms library or directory, scripts or modules are used interchangeably. A Python macro refers to a function inside a module.

warning

Note that <User Profile>/Scripts/python/pythonpath local directory is always explored when running a Python macro from <User Profile>/Scripts/python.


File System module import

LibreOffice Basic libraries contain classes, routines and variables, Python modules contain classes, functions and variables. Common pieces of reusable Python or UNO features must be stored in My macros within (User Profile)/Scripts/python/pythonpath. Python libraries help organize modules in order to prevent module name collisions. Import uno.py inside shared modules.

User or Shared Modules

Personal & shared Python scripts can be imported once their directories are included in Python run time path. Refer to Getting session information page for more details regarding omitted Session Class.


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
        import sys
            
        user_lib = Session().UserPythonScripts  # Localització dels scripts de l'usuari
        if not user_lib in sys.path:
            sys.path.insert(0, user_lib)  # Add to search path
        importa screen_io com a ui # el mòdul 'screen_io.py' està ubicat al directori user_lib
        # El vostre codi comença a partir d'aquí
    

Aquest exemple en Python exposa una variable local, XSCRIPTCONTEXT, a un mòdul importat:


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
        import uno, sys
            
        share_lib = Session.SharedPythonScripts()  # Localització dels scripts compartits
        if not share_lib in sys.path:
            sys.path.insert(0 share_lib) # Afegeix al camí de cerca
        des d'IDE_utils importeu ScriptContext # 'IDE_utils.py' es troba amb els scripts de Python compartits.
        XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
        # El vostre codi comença a partir d'aquí
    

Mòduls d'instal·lació per a aplicacions

A diferència dels scripts personals i compartits, els scripts d'instal·lació de LibreOffice es poden importar en qualsevol moment. Al costat dels mòduls Python de LibreOffice uno & unohelper, altres scripts presents al directori <installation_path>/program es poden importar directament, com el mòdul msgbox.

Amb l'intèrpret per a Python:

>>> 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"))

Document Module Import

Importing a Python document embedded module is illustrated below. Error handling is not detailed. Python run time path is updated when document has been opened and before closure. Refer to Event-Driven Macros to learn how to associate Python macros to document events.


        # -*- coding: utf-8 -*-
        from __future__ import unicode_literals
            
        import sys, uno
            
        def OnDocPostOpenLoadPython():
            """ Prepare Python modules import when doc. loaded """
            PythonLibraries.loadLibrary('lib/subdir')  # Add directory to search path
            PythonLibraries.loadLibrary('my_gui', 'screen_io')  # Add dir. & import screen_io
            
        def OnDocQueryCloseUnloadPython():
            """ Cleanup PYTHON_PATH when doc. Gets closed """
            PythonLibraries.unloadLibrary('my_gui')  # Python runtime path cleanup
            # Note: imported modules remain loaded in this example.
            
        class PythonLibraries():
            """ Python library loader and module importer
            
            adaptació de «Bibliothèque de fonctions» d'Hubert Lambert
            at https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213 """
            def isImportedModule(module_name: str) -> bool:
                """ Check run time module list """
                return (module_name in sys.modules.keys())
            def isLoadedLibrary(lib_name: str) -> bool:
                """ Check PYTHON_PATH content """
                return (lib_name in sys.path)
            def loadLibrary(lib_name: str, module_name=None):
                """ add directory to PYTHON_PATH, import named module """
                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):
                """ remove directory from PYTHON_PATH """
                sys.path.remove(lib_name)
            
        g_exportedScripts = (OnDocPostOpenLoadPython, OnDocQueryCloseUnloadPython)