Kalde Python-scripts fra Basic
Kalde Python-scripts fra LibreOffice Basic makroer er muligt, og værdifulde funktioner kan opnås, så som:
ComputerName identifikation eller OSName detektering er muligt,
Basic FileLen() funktion og com.sun.star.ucb.SimpleFileAccess.getSize() API-funktion udstiller en 2 Gigabyte filbegrænsning som Python kan afhjælpe,
com.sun.star.util.PathSettings kan blive normaliseret,
og mange andre.
Et fornuftig kendskab til LibreOffice Basic og til Application Programming Interface (API)-funktioner er anbefalet før du giver dig i kast med kald fra Basic til Python, til JavaScript eller andre typer scripts.
Hente Python-scripts
Python-scripts kan være personlige, delte eller indlejret i dokumenter. For at kunne udløse dem, skal LibreOffice Basic udstyres med Python-scriptets placering. Ved hjælp af com.sun.star.script.provider.XScript interface-kompatible UNO-objekter tillader udførelse af Python-scripts:
Option Explicit
Public Function GetPythonScript(macro As String, _
Optional location As String) As com.sun.star.script.provider.Xscript
''' Fang Python-script objekt før udførelsen
' Argumenter:
' makro : som "library/module.py$macro" eller "module.py$macro"
' placering: som "document", "share", "user" eller ENUM(eration)
' Resultat:
' ved 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 kompatibel
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
Udløse Python-scripts
Syntaks
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())
Eksempler med indlejrede scripts
Herunder vil ComputerName, og GetFilelen- rutiner blive kaldt med deres Python-version ved hjælp af førnævnte GetPythonScript-funktion. Håndtering af afvigelser er ikke detaljeret i eksemplerne.
Option Explicit
Option Compatible ' Egenskaber understøttes
Private scr As Object ' com.sun.star.script.provider.XScript
Private Property Get ComputerName As String
'''Maskinens navn'''
scr = GetPythonScript("Platform.py$computer_name", "document")
ComputerName = scr.invoke(Array(), Array(), Array())
End Property ' ComputerName
Private Function GetFilelen(systemFilePath As String) As Currency
'''Filstørrelse i 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 ' dokument-script
ISPERSONAL As String ' bruger-script
ISSHARED As String ' LibreOffice -makro
End Type ' _SCRIPT_LOCATION
Public Function Script() As Object ' Text enumeration
Static enums As _SCRIPT_LOCATION : With enums
If .ISEMBEDDED = "" Then
.ISEMBEDDED = "document" ' dokument-script
.ISPERSONAL = "user" ' bruger-scripts
.ISSHARED = "share" ' LibreOffice -makro
End If : End With ' enums
Script = enums
End Function ' Script
To forskellige Python-moduler kaldes. De kan enten integreres i det aktuelle dokument, eller lagres på filsystemet. Kontrol af argumenttype udelades fra eksemplerne for klarhedens skyld:
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)
Eksempler med personlige eller delte scripts
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 ' Egenskaber understøttes
Private scr As Object ' com.sun.star.script.provider.XScript
Private Property Get OSName As String
'''Platformsnavn som "Linux", "Darwin" eller "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
'''Fjern overflødige '\..' i sti'''
scr = GetPythonScript("Os/Path.py$normalyze", "user")
NormalizePath = scr.invoke(Array(systemFilePath), Array(), Array())
End Function ' NormalizePath
Python standardmoduler
LibreOffice indlejret Python har mange standardbiblioteker du kan drage nytte af. De tilbyder en række funktioner så som (men ikke begrænset til):
argparse Parser for kommandolinje egenskaber, argumenter og underkommandoer
cmath Matematiske funktioner for komplekse tal
csv Læse og skrive CSV-filer
datetime Typer for ægte dato og tid
json JSON indkoder og dekoder
math Matematiske funktioner
re Operationer med regulære udtryk
socket Lav-niveau netværksinterface
sys Systemspecifikke parametre og funktioner
unittest and trace Unit testing framework and Track Python execution
xml.etree.ElementTree ElementTree XML API