Ajuda del LibreOffice 7.3
És possible cridar scripts de Python des de macros de LibreOffice Basic, i es poden obtindre funcionalitats interessants com ara:
la possibilitat d'identificació ComputerName i la detecció de l'OSName,
Les funcions FileLen() del Basic i com.sun.star.ucb.SimpleFileAccess.getSize() de l'API tenen un límit màxim de la mida del fitxer de 2 Gigabytes que es pot superar amb Python,
Es pot normalitzar com.sun.star.util.PathSettings,
entre altres funcionalitats.
És recomanable familiaritzar-se amb les característiques de LibreOffice Basic i la interfície de programació d'aplicacions (API) abans de fer crides de Basic a Python, JavaScript o un altre motor de scripts.
Els scripts de Python poden ser independents, compartits o estar incrustats en els documents. Per a executar-los, s'han d'incloure les ubicacions dels scripts de Python en LibreOffice Basic. Cercar objectes UNO compatibles amb la interfície com.sun.star.script.provider.XScript permet que s'executen els scripts de Python:
Option Explicit
Public Function GetPythonScript(macro As String, _
Optional location As String) As com.sun.star.script.provider.Xscript
''' Pren l'objecte de l'script de Python abans de l'execució
' Arguments:
' macro : com a «library/module.py$macro» o «module.py$macro»
'····location: com a «document», «share», «user» o ENUM(eració)
' Resultat:
' s'ha localitzat el servei com.sun.star.script.provider.XScript de l'UNO'''
If IsMissing(location) Then location = "user"
Dim mspf As Object ' com.sun.star.script.provider.MasterScriptProviderFactory
Dim sp As Object ' compatible amb 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
workstation_name = script.invoke(Array(), Array(), Array())
opSysName = script.invoke(Array(), in_outs, Array()) ' in_out és una matriu
file_len = script.invoke(Array(systemFilePath), Array(), Array())
normalizedPath = script.invoke(Array(systemFilePath), Array(), Array())
Below ComputerName, and GetFilelen routines are calling their Python counterparts, using aforementioned GetPythonScript function. Exception handling is not detailed.
Option Explicit
Option Compatible ' S'admeten propietats
Private scr As Object ' com.sun.star.script.provider.XScript
Private Property Get ComputerName As String
'''Nom de l'estació de treball'''
scr = GetPythonScript("Platform.py$computer_name", "document")
ComputerName = scr.invoke(Array(), Array(), Array())
End Property ' ComputerName
Private Function GetFilelen(systemFilePath As String) As Currency
'''Mida del fitxer 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 ' script del document
ISPERSONAL As String ' script d'usuari
ISSHARED As String ' macro del LibreOffice
End Type ' _SCRIPT_LOCATION
Public Function Script() As Object ' Text enumeration
Static enums As _SCRIPT_LOCATION : With enums
If .ISEMBEDDED = "" Then
.ISEMBEDDED = "document" ' script del document
.ISPERSONAL = "user" ' scripts d'usuari
.ISSHARED = "share" ' macro del 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:
Platform.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import platform
def computer_name() -> str:
return platform.node()
def OSname() -> str:
return platform.system()
Os/Path.py
# -*- 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)
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 ' S'admeten propietats
Private scr As Object ' com.sun.star.script.provider.XScript
Private Property Get OSName As String
'''El nom d'una plataforma, com ara «Linux», «Darwin» o «Windows»'''
scr = GetPythonScript("Platform.py$OSname", Script.ISPERSONAL)
OSName = scr.invoke(Array(), Array(), Array())
End Property ' OSName
Private Sub HelloWorld()
'''exemple de Python compartit al LibreOffice'''
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
LibreOffice embedded Python contains many standard libraries to benefit from. They bear a rich feature set, such as but not limited to:
argparse Parser for command-line options, arguments and sub-commands
cmath: funcions matemàtiques per a nombres complexos
csv: lectura i escriptura de fitxers CSV
datetime: tipus de data i hora genuïns
json: codificador i descodificador de JSON
math: funcions matemàtiques
re: operacions amb expressions regulars
socket: interfície de xarxes de baix nivell
sys: paràmetres i funcions específiques del sistema
unittest i trace: entorn de proves unitàries i seguiment d'execució per a Python
xml.etree.ElementTree: API d'ElementTree XML