Calling Basic Macros from Python

Makra LibreOffice Basic można wywoływać ze skryptów Pythona, a w zamian można uzyskać znaczące funkcje, takie jak:

Struktura skryptów API (Application Programming Interface) LibreOffice obsługuje międzyjęzykowe wykonywanie skryptów między językami Python i Basic lub innymi obsługiwanymi językami programowania. Argumenty mogą być przekazywane tam iz powrotem między wywołaniami, pod warunkiem, że reprezentują prymitywne typy danych rozpoznawane przez oba języki i przy założeniu, że środowisko skryptowe odpowiednio je konwertuje.

tip

Zalecana jest znajomość standardowych modułów Pythona i funkcji API LibreOffice przed wykonaniem wywołań międzyjęzykowych z Pythona na Basic, JavaScript lub jakikolwiek inny silnik skryptowy.


warning

When running Python scripts from an Integrated Development Environment (IDE), the LibreOffice-embedded Basic engine may be absent. Avoid Python-to-LibreOffice Basic calls in such contexts. However Python environment and Universal Networks Objects (UNO) are fully available. Refer to Setting Up an Integrated IDE for Python for more information.


Pobieranie skryptów LibreOffice Basic

LibreOffice Basic macros can be personal, shared, or embedded in documents. In order to execute them, Python run time needs to be provided with Basic macro locations. Implementing the com.sun.star.script.provider.XScriptProvider interface allows the retrieval of executable scripts:


		 import uno
		 from com.sun.star.script.provider import Xscript
		     
		 def getBasicScript(macro='Main', module='Module1', library='Standard',
		         isEmbedded=False) -> XScript:
		     '''Chwyć obiekt skryptu Basic przed wywołaniem.'''
		     ctx = uno.getComponentContext()
		     smgr = ctx.ServiceManager
		     if isEmbedded:
		         desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)
		         scriptPro = desktop.CurrentComponent.getScriptProvider()
		         location = "document"
		     else:
		         mspf = smgr.createInstanceWithContext(
		             "com.sun.star.script.provider.MasterScriptProviderFactory", ctx)
		         scriptPro = mspf.createScriptProvider("")
		         location = "application"
		     scriptName = "vnd.sun.star.script:"+library+"."+module+"."+macro+ \
		                  "?language=Basic&location="+location
		     xScript = scriptPro.getScript(scriptName)
		     return xScript
		 

Wykonywanie skryptów LibreOffice Basic

The LibreOffice Software Development Kit (SDK) documentation for com.sun.star.script.provider.XScript interface details the calling convention for inter-language calls. Invocation of functions requires three arrays:

Składnia Pythona

results = script.invoke((prompt,buttons,title), (), ())

script.invoke((message,), tuple, ())

script.invoke((args), (), results)

Przykłady skryptów osobistych lub udostępnionych

Examples in Input/Output to Screen detail Python to Basic invocation calls. Monitoring Document Events illustrates the usage of *args Python idiom to print a variable number of parameters to Access2Base logging console dialog.

tip

At time of development you can interrupt Python script execution using Xray extension in order to inspect properties and methods of UNO objects. The APSO extension debugger allows object introspection using either Xray either MRI extensions.



	  def xray(myObject):
	  	  script = getBasicScript(library="XrayTool", module="_Main", macro="Xray")
	  	  script.invoke((myObject,), (), ())
	  

Przykłady osadzonych skryptów w dokumentach

W przypadku podstawowych funkcji programu LibreOffice, które akceptują zmienną liczbę argumentów, można użyć uproszczonej składni języka Python *args. Poniższe funkcje Pythona Print i SUM wywołują odpowiednie funkcje podstawowe Print i SUM przy użyciu wspomnianej funkcji getBasicScript. Obsługa błędów nie jest uwzględniona w kodzie.


	  # -*- coding: utf-8 -*-
	  from __future__ import unicode_literals
	      
	  def Print(*args):
	      """Wypisuje określony ciąg znaków lub wyrażenie liczbowe w oknie dialogowym."""
	      xScript = getBasicScript("Print", "Scripting", embedded=True)
	      xScript.invoke((args), (), ())
	      
	  def SUM(*args):
	      """SUM podanego wyrażenia liczbowego."""
	      xScript = getBasicScript("SUM", "Scripting", embedded=True)
	      res = xScript.invoke((args), (), ())
	      return res[0]
	      
	  # def getBasicScript()  # see above
	      
	  def playWithArgs():
	      Print("Fun with *args ", -9.81, 297864.681974, 8762E-137)
	      Print(SUM(45, -9.81, 297864.681974))
	      Print(SUM(45, -9.81, 297864.681974, 8762E+137))
	      
	  g_exportedScripts = (playWithArgs,)
	  

Podstawowe procedury LibreOffice Print i SUM oparte na dokumentach akceptują zmienną liczbę argumentów. Atrybuty Private lub Public nie działają. Sprawdzanie typu argumentów jest pomijane dla przejrzystości.


	  Option Compatible ' "Standard.Scripting" module
	  Option Explicit
	      
	  Private Sub Print(ParamArray args() As Variant, Optional sep As String = " ")
	      ''' Wyświetl listę pozycji o numerze zmiennej '''
	      ' wszystkie konwertowalne argumenty CStr() są akceptowane
	      Dim str As String, i As Integer
	      If UBound(args) >= 0 Then
	          For i = 0 To UBound(args)
	              str = str + Cstr(args(i))+ sep 
	          Next i
	      End If
	      Print str
	  End Sub ' Standard.Scripting.Print()
	      
	  Public Function SUM(ParamArray args() As Variant) As Variant
	      ''' SUM to zmienna lista liczb '''
	      Dim ndx As Integer
	      If UBound(args) >= 0 Then
	          For ndx = 0 To UBound(args)
	              SUM = SUM + args(ndx)
	          Next ndx
	      End If
	  End Function ' Standard.Scripting.SUM()