Ayuda de Collabora Office 24.04
Collabora Office 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.
Note that <User Profile>/Scripts/python/pythonpath local directory is always explored when running a Python macro from <User Profile>/Scripts/python.
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 # Ubicación de las secuencias de órdenes del usuario
if not user_lib in sys.path:
sys.path.insert(0, user_lib) # Añadir a la ruta de búsqueda
import screen_io as ui # el módulo «screen_io.py» se encuentra en el directorio user_lib
# Su código comienza a partir de aquí
Este ejemplo de Python expone una variable local, XSCRIPTCONTEXT, a un módulo importado:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import uno, sys
share_lib = Session.SharedPythonScripts() # Ubicación de las secuencias compartidas
if not share_lib in sys.path:
sys.path.insert(0, share_lib) # Añadir a la ruta de búsqueda
from IDE_utils import ScriptContext # «IDE_utils.py» se encuentra en las secuencias de órdenes Python compartidas.
XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
# Su código comienza a partir de aquí
A diferencia de las secuencias personales y compartidas, siempre es posible importar las secuencias instaladas por Collabora Office. Junto con los módulos Python uno y unohelper de Collabora Office, es posible importar otras secuencias que estén en el directorio <ruta de la instalación>/program, como es el caso del módulo msgbox.
Con el intérprete de 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"))
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
# Nota: los módulos importados permanecen cargados en este ejemplo.
class PythonLibraries():
""" Cargador de bibliotecas e importador de módulos para Python
adaptado de la «Bibliothèque de fonctions» de Hubert Lambert
en https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213 """
def isImportedModule(module_name: str) -> bool:
""" Comprobar lista de módulos de tiempo de ejecución """
return (module_name in sys.modules.keys())
def isLoadedLibrary(lib_name: str) -> bool:
""" Comprobar contenido de PYTHON_PATH """
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):
""" quitar el directorio de PYTHON_PATH """
sys.path.remove(lib_name)
g_exportedScripts = (OnDocPostOpenLoadPython, OnDocQueryCloseUnloadPython)