4eXWf‖Basic to Python

Contents
Ldq49‖

# GD9hZ‖Calling Python Scripts from Basic

P7E4G‖Calling Python scripts from LibreOffice Basic macros is possible, and valuable features can be obtained such as:

- ZKSB3‖ComputerName identification or OSName detection are possible,

- RW3Yq‖Basic FileLen() function and com.sun.star.ucb.SimpleFileAccess. getSize() API function exhibit a 2 Gigabytes file size upper limit that Python helps to overcome,

- UuEjr‖com.sun.star.util.PathSettings can be normalized,

- CPd9K‖and many more.

FdkpF‖A reasonable exposure to LibreOffice Basic and to Application Programming Interface (API) features is recommended prior to perform inter-language calls from Basic to Python, to JavaScript or any other script engine.

## 4jY8s‖Retrieving Python Scripts

rPSP7‖Python scripts can be personal, shared, or embedded in documents. In order to execute them, LibreOffice Basic needs to be provided with Python script locations. Locating com.sun.star.script.provider.XScript interface compliant UNO objects allows the execution of Python scripts:

             Option Explicit

             Public Function GetPythonScript(macro As String, _
                     Optional location As String) As com.sun.star.script.provider.Xscript
             vPFpG‖    ''' Grab Python script object before execution
             hgxff‖    ' Arguments:
             mBqrA‖    '    macro   : as "library/module.py$macro" or "module.py$macro"
             MRUh7‖    '    location: as "document", "share", "user" or ENUM(eration)
             DSEvB‖    ' Result:
             twhAb‖    '    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
             vrbXe‖    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

## osCpU‖Executing Python Scripts

fDXhz‖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 forth across calls, provided that they represent primitive data types that both languages recognize, and assuming that the Scripting Framework converts them appropriately.

### pAfKa‖Syntax

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

gVpsb‖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())

### jiU2w‖Embedded Scripts Examples

FadCx‖Below ComputerName, and GetFilelen routines are calling their Python counterparts, using aforementioned GetPythonScript function. Exception handling is not detailed.

             Option Explicit
             YbMbS‖Option Compatible ' Properties are supported

             Private scr As Object ' com.sun.star.script.provider.XScript

             Private Property Get ComputerName As String
             FCMed‖    '''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
             UqaWU‖    '''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
             dmw62‖    ISEMBEDDED As String ' document script
             QhLca‖    ISPERSONAL As String ' user script
             Vchg2‖    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
             97QM4‖        .ISEMBEDDED = "document" ' document script
             dfKju‖        .ISPERSONAL = "user" ' user scripts
             BmdRg‖        .ISSHARED = "share" ' LibreOffice macro
                 End If : End With ' enums
                 Script = enums
             End Function ' Script

KfKCA‖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)

### igPCi‖Personal or Shared Scripts Examples

EPVTC‖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
             bwkSJ‖Option Compatible ' Properties are supported

             Private scr As Object ' com.sun.star.script.provider.XScript

             Private Property Get OSName As String
             BeiyR‖    '''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()
             SpeQ6‖    '''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
             6ZgAS‖    '''Strip superfluous '\..' in path'''
                 scr = GetPythonScript("Os/Path.py$normalyze", "user")
                 NormalizePath = scr.invoke(Array(systemFilePath), Array(), Array())
             End Function ' NormalizePath

## yTqsy‖Python standard modules

3F9RQ‖LibreOffice embedded Python contains many standard libraries to benefit from. They bear a rich feature set, such as but not limited to:

- aPbV7‖argparse Parser for command-line options, arguments and sub-commands

- zBD3c‖cmath Mathematical functions for complex numbers

- GDXVa‖csv CSV files reading and writing

- FnCu8‖datetime Genuine date and time types

- GQCwa‖json JSON encoder and decoder

- JmFZK‖math Mathematical functions

- PRGHi‖re Regular expression operations

- XVbzW‖socket Low-level networking interface

- VehtJ‖sys System-specific parameters and functions

- RWzWY‖unittest and trace Unit testing framework and Track Python execution

- JG3VZ‖xml.etree.ElementTree ElementTree XML API

Related Topics

Calling Basic Macros from Python

LibreOffice Basic Help

LibreOffice Python Scripts Help

Please support us!