Text Documents (Writer)
HTML Documents (Writer Web)
Spreadsheets (Calc)
Presentations (Impress)
Drawings (Draw)
Database Functionality (Base)
Formulae (Math)
Charts and Diagrams
Macros and Scripting
Office Installation
Common Help Topics
OneOffice Logo

Importing Python Modules

Office Python scripts come in three distinct flavours, they can be personal, shared or embedded in documents. They are stored in varying places described in Python Scripts Organisation 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.

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

File System module import

Office 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 organise 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  # 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, Office installation scripts can be imported any time. Next to uno & unohelper Office Python modules, other scripts present in /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)