Innhold
Innholdsliste 🔎︎

# Importerer Phyton Moduler

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.

Denne mekanismen er illustrert for filsystembaserte moduler og dokumentbaserte moduler. Unntakshåndtering utelates for enkelhetens skyld. Vilkårs bibliotek eller katalog, skript eller moduler brukes om hverandre. En Python-makro refererer til en funksjon inne i en modul.

Noter at<User Profile>Scripts/python/pythonpathlokal katalog utforskes alltid når en Phyton makro kjøres fra<User Profile>/Scripts/python.

## Fil System modul 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.

### Bruker delte moduler

Personlige og delte Python-skript kan importeres når bibliotekene er importert i Python-kjøremiljøet. Se siden Hent informasjon for mer informasjon om utelatt sesjonsklasse.

            # -*- coding: utf-8 -*-
            from __future__ import unicode_literals
            import sys

            user_lib = Session().UserPythonScripts  # User scripts location
            if not user_lib in sys.path:
                sys.path.insert(0, user_lib)  # Add to search path
            import screen_io as ui  # 'screen_io.py' module resides in user_lib directory
            # Your code follows here

This Python example exposes a local XSCRIPTCONTEXT variable to an imported module:

            # -*- coding: utf-8 -*-
            from __future__ import unicode_literals
            import uno, sys

            share_lib = Session.SharedPythonScripts()  # Shared scripts location
            if not share_lib in sys.path:
                sys.path.insert(0, share_lib)  # Add to search path
            from IDE_utils import ScriptContext  # 'IDE_utils.py' sits with shared Python scripts.
            XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
            # Your code follows here

### Installation Modules for Applications

Unlike personal and shared scripts, LibreOffice installation scripts can be imported any time. Next to uno & unohelper LibreOffice Python modules, other scripts present in <installation_path>/program directory can be imported directly, such as the msgbox module.

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

## 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

                adapted from 'Bibliothèque de fonctions' by 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)

Lignende emner

Getting Session Information

Programmering med Python-skript

Organisering og plassering av Pythonskript

Refer to Creating a Python Listener for examples of event-driven macros.