Invocar secuencias de Python desde Basic

Se pueden invocar secuencias de Python desde las macros de LibreOffice Basic y así sacar provecho de funcionalidades como las siguientes:

tip

Se recomienda familiarizarse con las características de LibreOffice Basic y la interfaz de programación de aplicaciones (API) antes de realizar invocaciones interlenguaje desde Basic hacia Python, JavaScript u otro motor ejecución de scripts.


Recuperar secuencias de órdenes de Python

Las secuencias de Python pueden ser independientes, compartidas o estar incrustadas en los documentos. Para ejecutarlas, se deben incluir las ubicaciones de las secuencias de Python en LibreOffice Basic. Ubicando objetos UNO que se ajusten a la interfaz com.sun.star.script.provider.XScript permite que se ejecuten las secuencias de Python.


         Option Explicit
             
         Public Function GetPythonScript(macro As String, _
                 Optional location As String) As com.sun.star.script.provider.Xscript
             ''' Tomar el objeto con las secuencias de Python antes de ejecutar
             ' Argumentos:
             '    macro   : como «library/module.py$macro» o «module.py$macro»
             '    location: como «document», «share», «user» o ENUM(eración)
             ' Resultado:
             '    localizose el servicio de UNO com.sun.star.script.provider.XScript'''
             If IsMissing(location) Then location = "user"
             Dim mspf As Object ' com.sun.star.script.provider.MasterScriptProviderFactory
             Dim sp As Object ' compatible con com.sun.star.script.provider.XScriptProvider
             Dim uri As String
             If location="document" Then
                 sp = ThisComponent.getScriptProvider()
             Else
                 mspf = CreateUNOService("com.sun.star.script.provider.MasterScriptProviderFactory")
                 sp = mspf.createScriptProvider("")
             End If
             uri = "vnd.sun.star.script:"& macro &"?language=Python&location="& location
             GetPythonScript = sp.getScript(uri)
         End Function ' GetPythonScript
      

Ejecutar secuencias de órdenes de Python

The LibreOffice Application Programming Interface (API) Scripting Framework supports inter-language script execution between Python and Basic, or other supported programming languages for that matter. Arguments can be passed back and fourth across calls, providing they represent primitives data types that both languages recognize, and assuming that the Scripting Framework converts them appropriately.

Sintaxis

workstation_name = script.invoke(Array(), Array(), Array())

opSysName = script.invoke(Array(), in_outs, Array()) ' in_outs es un arreglo

file_len = script.invoke(Array(systemFilePath), Array(), Array())

normalizedPath = script.invoke(Array(systemFilePath), Array(), Array())

Ejemplos de secuencias de órdenes incrustadas

Below ComputerName, and GetFilelen routines are calling their Python counterparts, using aforementioned GetPythonScript function. Exception handling is not detailed.


         Option Explicit
         Option Compatible ' Se admiten propiedades
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get ComputerName As String
             '''Nombre de la estación de trabajo'''
             scr = GetPythonScript("Platform.py$computer_name", "document")
             ComputerName = scr.invoke(Array(), Array(), Array())
         End Property ' ComputerName
             
         Private Function GetFilelen(systemFilePath As String) As Currency
             '''Tamaño del archivo en bytes'''
             scr = GetPythonScript("Os/Path.py$get_size", Script.ISEMBEDDED)
             GetFilelen = scr.invoke(Array(systemFilePath), Array(), Array(),)
         End Function ' GetFilelen
             
         Private Type _SCRIPT_LOCATION
             ISEMBEDDED As String ' secuencia de órdenes del documento
             ISPERSONAL As String ' secuencia de órdenes del usuario
             ISSHARED As String ' macro de LibreOffice
         End Type ' _SCRIPT_LOCATION
             
         Public Function Script() As Object ' Text enumeration
             Static enums As _SCRIPT_LOCATION : With enums
             If .ISEMBEDDED = "" Then
                 .ISEMBEDDED = "document" ' secuencia de órdenes del documento
                 .ISPERSONAL = "user" ' secuencias de órdenes del usuario
                 .ISSHARED = "share" ' macro de LibreOffice
             End If : End With ' enums
             Script = enums
         End Function ' Script
      

Two different Python modules are called. They can either be embedded in the current document, either be stored on the file system. Argument type checking is skipped for clarity:


         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
          
         import platform
          
         def computer_name() -> str:
             return platform.node()
          
         def OSname() -> str:
             return platform.system()
      

         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
          
         import os.path
          
         def get_size(systemFilePath: str) -> str:
             return str(os.path.getsize(systemFilePath))
          
         def normalyze(systemPath: str) -> str:
             return os.path.normpath(systemPath)
      

Personal or Shared Scripts Examples

The calling mechanism for personal or shared Python scripts is identical to that of embedded scripts. Library names are mapped to folders. Computing LibreOffice user profile and shared modules system file paths can be performed as detailed in Getting session information. Below OSName, HelloWorld and NormalizePath routines are calling their Python counterparts, using aforementioned GetPythonScript function. Exception handling is not detailed.


         Option Explicit
         Option Compatible ' Se admiten propiedades
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get OSName As String
             '''Nombre de plataforma, como «Linux», «Darwin» o «Windows»'''
             scr = GetPythonScript("Platform.py$OSname", Script.ISPERSONAL)
             OSName = scr.invoke(Array(), Array(), Array()) 
         End Property ' OSName
             
         Private Sub HelloWorld()
             '''ejemplo de Python compartido en LibreOffice'''
             scr = GetPythonScript("HelloWorld.py$HelloWorldPython", Script.ISSHARED)
             scr.invoke(Array(), Array(), Array(),)
         End Sub ' HelloWorld
             
         Public Function NormalizePath(systemFilePath As String) As String
             '''Quitar el «\..» superfluo de la ruta'''
             scr = GetPythonScript("Os/Path.py$normalyze", "user")
             NormalizePath = scr.invoke(Array(systemFilePath), Array(), Array())
         End Function ' NormalizePath
      

Módulos estándares de Python

La versión de Python incluida en LibreOffice contiene numerosas bibliotecas estándares que puede aprovechar. Entre sus funcionalidades se encuentran:

¡Necesitamos su ayuda!