Programar con secuencias de órdenes en Python

A Python macro is a function within a .py file, identified as a module. Unlike LibreOffice Basic and its dozen of UNO objects functions or services, Python macros use the XSCRIPTCONTEXT UNO single object, shared with JavaScript and BeanShell. The g_exportedScripts global tuple explicitly lists selectable macros from a module. Python modules hold autonomous code logic, and are independent from one another.

Variable global XSCRIPTCONTEXT

Genuine Basic UNO facilities can be inferred from XSCRIPTCONTEXT global variable. Refer to LibreOffice API for a complete description of XSCRIPTCONTEXT. XSCRIPTCONTEXT methods summarize as:

Métodos

Descripción

Mapeado en Basic como

getDocument()

La referencia del documento en el que puede funcionar la macro.

ThisComponent

getDesktop()

La referencia del escritorio en la que puede funcionar la macro.

StarDesktop

getComponentContext()

El contexto del componente que la macro puede utilizar para crear otros componentes UNO.

GetDefaultContext


HelloWorld y Capitalise instaladas en las macros compartidas, ilustra las macros relacionadas con UNO, haciendo uso de la variable globalXSCRIPTCONTEXT.

tip

La salida estándar de Python no está disponible cuando se ejecutan macros de Python desde el menú Herramientas ▸ Macros ▸ Ejecutar macro. Consulte Entrada/salida de y hacia la pantalla para obtener más información.


Importación de módulos

warning

XSCRIPTCONTEXT no se proporciona a los módulos importados.


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.

Genuine BASIC UNO facilities can be inferred using uno.py module. Use Python interactive shell to get a complete module description using dir() and help() Python commands.

Funciones

Descripción

Mapeado en Basic como

absolutize()

Devuelve una url de archivo absoluta de las urls proporcionadas.

createUnoStruct()

Crea una estructura UNO o excepción dada por typeName.

CreateUNOStruct()

fileUrlToSystemPath()

Devuelve una ruta del sistema.

ConvertFromURL()

getClass()

Devuelve la clase de una excepción, una estructura o una interfaz de UNO concreta.

getComponentContext()

Devuelve el contexto del componente de UNO utilizado para iniciar el entorno de ejecución de Python.

GetDefaultContext()

Enum()

getConstantByName()

Busca el valor de una constante de IDL dando su nombre explícito.

Ver grupos constantes de API

isInterface()

Devuelve Verdadero, cuando el objeto es una clase de una interfaz UNO

systemPathToFileUrl()

Devuelve una URL de archivo para la ruta del sistema proporcionada

ConvertToURL()


LibreLogo y TableSample instalados en las macros compartidas use el modulouno.py.

Más ejemplos Python-Basic

UNO en Python

Funcionalidades básicas de UNO

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

obj = smgr.createInstanceWithContext( .. , ctx)

CreateUnoService()

See Opening a Dialog

CreateUnoDialog()

See Creating a Listener

CreateUnoListener()

Ver tipos de datos UNO

CreateUnoValue()

CreateObject()

EqualUnoObjects()

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

GetProcessServiceManager()

def hasUnoInterfaces(obj, *interfaces):

return set(interfaces).issubset(t.typeName for t in obj.Types)

HasUnoInterfaces()

IsUnoStruct()

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

DESK = 'com.sun.star.frame.Desktop'

desktop = smgr.createInstanceWithContext(DESK , ctx)

StarDesktop

desktop = smgr.createInstanceWithContext(DESK , ctx)

doc = desktop.CurrentComponent

ThisComponent


Importación de un módulo integrado

Similarly to LibreOffice Basic that supports browsing and dynamic loading of libraries, Python libraries can be explored and imported on demand. For more information on library containers, visit LibreOffice Application Programming Interface (API) or download LibreOffice Software Development Kit (SDK).

A continuación se ilustra la importación de un módulo Python incrustado en un documento, la gestión de excepciones no está detallada:


            import uno, sys
            
            def load_library(library_name: str, module_name=None):
                """ carga de biblioteca e importación de módulo
                
                Adaptado de «Bibliothèque de fonctions» de Hubert Lambert
                en https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213"""
                doc = XSCRIPTCONTEXT.getDocument()  # documento actual
                url = uno.fileUrlToSystemPath( \
                    '{}/{}'.format(doc.URL, 'Scripts/python'+library_name))  # ConvertToURL()
                if not url in sys.path:  # adición de ruta, si es necesario
                    sys.path.insert(0, url)  # el doclib tiene prioridad
                if module_name:  # se importa si se solicita
                    return zipimport.zipimporter(url).load_module(module_name)
            
            def import_embedded_python():
                ui = load_library("my_gui",'screen_io')  # agrega <lib> ruta + import <module>
                ui.MsgBox(sys.modules.keys())
            
            g_exportedScripts = (import_embedded_python,)  # Public macros
        

¡Necesitamos su ayuda!