Ayuda de LibreOffice 25.2
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.
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 | Correlacionado en Basic con | 
|---|---|---|
| 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.
La salida estándar de Python no está disponible cuando se ejecutan macros de Python desde el menú . Consulte Entrada/salida de y hacia la pantalla para obtener más información.
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 | Correlacionado en Basic con | 
|---|---|---|
| absolutize() | Devuelve un URL de archivo absoluto a partir de los URL proporcionados. | |
| 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 un URL de archivo para la ruta del sistema proporcionada. | ConvertToURL() | 
Las secuencias de órdenes preinstaladas LibreLogo, NamedRanges, SetCellColor y TableSample usan el módulo uno.py.
| UNO en Python | Funcionalidades básicas de UNO | 
|---|---|
| ctx = uno.getComponentContext() smgr = ctx.getServiceManager() obj = smgr.createInstanceWithContext( .. , ctx) | CreateUnoService() | 
| See Opening a Dialog | CreateUnoDialog() | 
| CreateUnoListener() | |
| Ver tipos de datos UNO | CreateUnoValue() CreateObject() | 
| Usar operadores de comparación «==» o «!=» | 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 | 
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).
Importing a Python document embedded module is illustrated below, exception handling is not detailed:
            import uno, sys, zipimport
            
            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