Richiamare script Python da Basic

È possibile richiamare script Python dalle LibreOffice macro di Basic e si possono ottenere valide funzioni, come ad esempio:

tip

È consigliabile un adeguato approccio a LibreOffice Basic e ad Application Programming Interface (API) prima di eseguire funzioni di chiamata tra linguaggi Basic, Python, JavaScript o qualsiasi altro motore di script.


Richiamo degli script Python

Gli script Python possono essere personali, condivisi o incorporati nei documenti. Per poterli eseguire, LibreOffice Basic deve disporre della posizione degli script Python. L'individuazione di oggetti UNO compatibili con l'interfaccia com.sun.star.script.provider.XScript consente l'esecuzione di script Python:


         Option Explicit
             
         Public Function GetPythonScript(macro As String, _
                 Optional location As String) As com.sun.star.script.provider.Xscript
             ''' Grab Python script object before execution
             ' Arguments:
             '    macro   : as "library/module.py$macro" or "module.py$macro"
             '    location: as "document", "share", "user" or ENUM(eration)
             ' Result:
             '    located com.sun.star.script.provider.XScript UNO service'''
             If IsMissing(location) Then location = "user"
             Dim mspf As Object ' com.sun.star.script.provider.MasterScriptProviderFactory
             Dim sp As Object ' com.sun.star.script.provider.XScriptProvider compatible
             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
      

Esecuzione degli script 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.

Sintassi

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

opSysName = script.invoke(Array(), in_outs, Array()) ' in_out is an Array

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

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

Esempi di script incorporati

Le routine seguenti ComputerName e GetFilelen richiamano le corrispondenti controparti Python mediante la funzione GetPythonScript precedentemente menzionata. La gestione delle eccezioni non è dettagliata.


         Option Explicit
         Option Compatible ' Properties are supported
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get ComputerName As String
             '''Workstation name'''
             scr = GetPythonScript("Platform.py$computer_name", "document")
             ComputerName = scr.invoke(Array(), Array(), Array())
         End Property ' ComputerName
             
         Private Function GetFilelen(systemFilePath As String) As Currency
             '''File size in 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 ' document script
             ISPERSONAL As String ' user script
             ISSHARED As String ' LibreOffice macro
         End Type ' _SCRIPT_LOCATION
             
         Public Function Script() As Object ' Text enumeration
             Static enums As _SCRIPT_LOCATION : With enums
             If .ISEMBEDDED = "" Then
                 .ISEMBEDDED = "document" ' document script
                 .ISPERSONAL = "user" ' user scripts
                 .ISSHARED = "share" ' LibreOffice macro
             End If : End With ' enums
             Script = enums
         End Function ' Script
      

Vengono richiamati due diversi moduli Python. Possono essere incorporati nel documento corrente o memorizzati nel file system. Il controllo del tipo di argomento per chiarezza viene tralasciato:


         # -*- 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)
      

Esempi di script personali o condivisi

Il meccanismo di chiamata per script Python personali o condivisi è identico a quello degli script incorporati. I nomi delle librerie sono mappati in cartelle. L'elaborazione del profilo utente LibreOffice e dei percorsi dei file di sistema relativi ai moduli condivisi si possono eseguire come descritto in Ottenere informazioni sulla sessione. Le routine seguenti OSName, HelloWorld e NormalizePath richiamano le corrispondenti controparti Python mediante la funzione GetPythonScript precedentemente menzionata. La gestione delle eccezioni non è dettagliata.


         Option Explicit
         Option Compatible ' Properties are supported
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get OSName As String
             '''Platform name as "Linux", "Darwin" or "Windows"'''
             scr = GetPythonScript("Platform.py$OSname", Script.ISPERSONAL)
             OSName = scr.invoke(Array(), Array(), Array()) 
         End Property ' OSName
             
         Private Sub HelloWorld()
             '''LibreOffice Python shared sample'''
             scr = GetPythonScript("HelloWorld.py$HelloWorldPython", Script.ISSHARED)
             scr.invoke(Array(), Array(), Array(),)
         End Sub ' HelloWorld
             
         Public Function NormalizePath(systemFilePath As String) As String
             '''Strip superfluous '\..' in path'''
             scr = GetPythonScript("Os/Path.py$normalyze", "user")
             NormalizePath = scr.invoke(Array(systemFilePath), Array(), Array())
         End Function ' NormalizePath
      

Moduli Python standard

I moduli Python incorporati in LibreOffice contengono molte librerie standard da cui trarre vantaggio. Offrono una ricca gamma di funzioni, comprese, ma non esclusivamente, le seguenti: