Python-scripts vanuit BASIC aanroepen

Python-scripts aanroepen vanuit LibreOffice Basismacro's is mogelijk en waardevolle functies kunnen worden verkregen, zoals:

tip

Een passende afhandeling van LibreOffice BASIC en de Application Programming Interface (API) wordt voorafgaand aan het aanroepen vanuit BASIC naar Python, JavaScript of een andere script-engine aanbevolen.


Python-scripts ophalen

Python-scripts kunnen persoonlijk, gedeeld of ingesloten zijn in documenten. Om ze uit te voeren, moet LibreOffice Basic worden voorzien van Python-scriptlocaties. Het vinden van com.sun.star.script.provider.XScript interface-compatibele UNO-objecten maken de uitvoering van Python-scripts mogelijk:


         Option Explicit
             
         Public Function GetPythonScript(macro As String, _
                 Optional location As String) As com.sun.star.script.provider.Xscript
             ''' Haalt het Python-scriptobject op voordat het wordt uitgevoerd
             ' Argumenten:
             '    macro   : als "library/module.py$macro" of "module.py$macro"
             '    locatie: als "document", "share", "user" of ENUM(eration)
             ' Resultaat:
             '    gevonden 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 compatibel
             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
      

Python-scripts uitvoeren

De LibreOffice Application Programming Interface (API) Scripting Framework ondersteunt uitvoering van scripts tussen Python en Basic of andere ondersteunde programmeertalen. Argumenten kunnen worden teruggegeven en doorgegeven bij aanroepen, als die tenminste van een data-type zijn dat door beide talen wordt ondersteund en aannemende dat het Scripting Framework ze goed converteert.

Syntaxis

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

opSysName = script.invoke(Matrix(), in_outs, Matrix()) ' in_out is een Matrix

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

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

Voorbeelden van insloten scripts

Onder de Computernaam en GetFilelen routines worden hun Python-tegenhangers aangeroepen met behulp van de eerder genoemde GetPythonScript functie. Uitzonderingsafhandeling is niet gedetailleerd.


         Option Explicit
         Compatibele optie-eigenschappen worden ondersteund
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get ComputerName As String
             '''Naam werkstation'''
             scr = GetPythonScript("Platform.py$computer_name", "document")
             ComputerName = scr.invoke(Array(), Array(), Array())
         End Property ' ComputerName
             
         Private Function GetFilelen(systemFilePath As String) As Currency
             '''Bestandsgrootte 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 ' documentscript
             ISPERSONAL As String ' gebruikersscript
             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" ' documentscript
                 .ISPERSONAL = "user" ' gebruikersscripts
                 .ISSHARED = "share" ' LibreOffice-macro
             End If : End With ' enums
             Script = enums
         End Function ' Script
      

Twee verschillende Python-modules worden genoemd. Ze kunnen worden ingesloten in het huidige document of worden opgeslagen in het bestandssysteem. Controle van argumenttypen wordt voor de duidelijkheid overgeslagen:


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

Voorbeelden van persoonlijke of gedeelde scripts

Het aanroepmechanisme voor persoonlijke of gedeelde Python-scripts is identiek aan dat van ingesloten scripts. Bibliotheeknamen worden toegewezen aan mappen. De berekening van de systeembestandspaden voor LibreOffice gebruikersprofielen en gedeelde modules kan worden gedaan zoals in Sessie-informatie ophalen. Onder OSName, HelloWorld en NormalizePath routines roepen hun Python-tegenhangers op, met behulp van de eerder genoemde GetPythonScript functie. Uitzonderingsafhandeling is niet gedetailleerd.


         Option Explicit
         Optiecompatibele ' Eigenschappen worden ondersteund
             
         Private scr As Object ' com.sun.star.script.provider.XScript
             
         Private Property Get OSName As String
             '''Platformnaam zoals "Linux", "Darwin" of "Windows"'''
             scr = GetPythonScript("Platform.py$OSname", Script.ISPERSONAL)
             OSName = scr.invoke(Array(), Array(), Array()) 
         End Property ' OSName
             
         Private Sub HelloWorld()
             '''Algemeen LibreOffice Python-voorbeeld'''
             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 pad'''
             scr = GetPythonScript("Os/Path.py$normalyze", "user")
             NormalizePath = scr.invoke(Array(systemFilePath), Array(), Array())
         End Function ' NormalizePath
      

Python standaardmodules

In LibreOffice ingesloten Python bevat veel standaardbibliotheken om van te profiteren. Ze hebben een rijke functieset, zoals maar niet beperkt tot:

Help ons, alstublieft!