Knihovna Scriptforge je k dispozici pro jazyky Basic a Python. Většina služeb, metod a vlastností funguje v obou programovacích jazycích stejně. Vzhledem k odlišnostem mezi nimi si však uživatel používající ScriptForge v Pythonu musí být vědom některých charakteristik této knihovny:
Názvy metod a vlastností: V Pythonu lze pro názvy metod a vlastností použít formát s malými písmeny (lowercased), s velkými písmeny na začátku slov (ProperCased) nebo s prvním písmenem malým a ostatními velkými (camelCased).
Arguments: All keyword arguments passed on to methods are lowercased.
Data: Všechny objekty představující datum jsou předávány a vraceny jako nativní objekty Pythonu typu datetime.datetime.
Pole: Jednorozměrná pole jsou předávána a vracena jako n-tice (což je nezměnitelný objekt). Dvourozměrná pole jsou předávána a vracena jako n-tice n-tic.
None: Klíčové slovo Pythonu None odpovídá v Basicu Null, Empty nebo Nothing.
Objekty UNO: Všechny struktury UNO se mezi Basicem a Pythonem předávají bez jakýchkoliv změn.
Ladění: Nastane-li ve skriptu Pythonu využívajícím knihovnu ScriptForge chyba, chybová zpráva poskytnutá prostředím Pythonu obsahuje řádek kódu, který chybu vyvolal. V chybových zprávách Basicu tato informace není.
Úprava skriptů Pythonu ve vývojových prostředích (IDE)
Ve vývojových prostředích (IDE) s příslušnou funkcí lze získat pro Python typovou nápovědu týkající se veřejných metod a vlastností knihovny ScriptForge. Při úpravě uživatelského skriptu:
se při najetí na instanci, metodu, nebo vlastnost objektu zobrazí podrobný popis.
po zapsání "." za instanci objektu se zobrazí rozbalovací pole s výpisem všech dostupných rozhraní.
po zapsání závorky za názvem metody se spustí doplňování kódu a zobrazí se argumenty této metody.
Typová nápověda se zobrazí pouze tehdy, je-li v názvech upravovaných metod a vlastností použita správná velikost písmen.
Spouštění skriptů Pythonu v LibreOfficeDev
Podle toho, čeho hodláte dosáhnout, můžete zvolit jeden z následujících přístupů, jak spouštět skripty Pythonu v LibreOfficeDev:
Spouštět skripty v rámci aktuálního procesu LibreOfficeDev: Skripty Pythonu jsou spouštěny v rámci procesu LibreOfficeDev volbou z nabídky Nástroje - Makra - Spustit makro nebo pomocí rozšíření APSO, který se volají uživatelské skripty uložené ve složce se skripty Pythonu. Shell Pythonu APSO můžete také využít pro interaktivní spouštění skriptů Pythonu.
Spouštět skripty odděleně od procesu LibreOfficeDev: Skripty Pythonu se spouští z externího procesu, který se připojí k běžícímu procesu LibreOfficeDev pomocí roury (pipe) nebo socketu.
Plánujete-li spouštět skripty v rámci procesu LibreOfficeDev, doporučuje se nainstalovat rozšíření APSO (Alternative Script Organizer for Python). K vývoji skriptů Pythonu mimo LibreOfficeDev však můžete zvolit svoje oblíbené integrované vývojové prostředí (IDE).
Spouštění skriptů v rámci procesu LibreOfficeDev
Pomocí rozšíření APSO
The easiest way to get started with Python scripting in LibreOfficeDev is by installing the APSO extension. After installing it, open any LibreOfficeDev component and go to Tools - Macros - Organize Python Scripts.
In APSO's main window go to Menu - Python Shell.
Alternatively you can open APSO using the default shortcut Alt + Shift + F11.
Now you can start typing Python commands and the shell will print the corresponding output after each line of code is executed.
To start using the ScriptForge library, you need to import the CreateScriptService method, with which you will be able to access the services provided by the library. The example below uses the Basic service to display a message box.
from scriptforge import CreateScriptService
bas = CreateScriptService("Basic")
bas.MsgBox("Hello!")
To run the example above, enter each line in the Python shell, one by one, pressing the Enter key after you type each line of code.
Now you can start executing Python commands using any of the ScriptForge services. For example, the code snippet below uses the UI service to create a blank Writer document.
Now you can create a text file inside your Python user scripts folder, for instance my_script.py, and start typing your scripts.
Next is a simple example that gets the numeric value from a Calc cell and increments it by 1. Simply type the following code into my_script.py file.
from scriptforge import CreateScriptService
doc = CreateScriptService("Calc")
def increment_cell(args=None):
value = doc.GetValue("A1")
value += 1
doc.SetValue("A1", value)
g_exportedScripts = (increment_cell, )
This example creates the increment_cell function. Note that g_exportedScripts is a tuple that tells which functions will be displayed in LibreOfficeDev as user scripts.
To run this script from within a Calc document:
Create or open a Calc file.
Enter some numeric value into cell "A1" in the current sheet.
Go to Tools - Macros - Run Macros .
Choose My Macros - my_script in the library selector. Then choose the increment_cell function under the Macro Name list.
Click Run. Note that the value in cell "A1" was incremented by 1.
You can also use APSO to run Python scripts in a similar manner:
First open APSO by going to Tools - Macros - Organize Python Scripts.
In the macro list, navigate to My Macros - my_script - increment_cell.
Click Execute.
Running Scripts separately from the LibreOfficeDev process
Determining the Installation Path
The first step to run scripts from a separate process is to find the folder where LibreOfficeDev is installed. There are several ways to do that, but ScriptForge provides a quick way to identify your installation path. For that, open APSO's Python shell and type:
The output from the code above is the base directory where LibreOfficeDev is installed. Now you need to add the "program" subfolder to the resulting path. This is the base folder from which you will run Python scripts from a separate process.
For example, suppose you get /usr/lib/libreoffice/ as the result from running the Python code above. Then you need to consider /usr/lib/libreoffice/program as the path to run your Python scripts.
Start LibreOfficeDev with pipe or socket settings
To run Python scripts from a separate process, you need to start LibreOfficeDev with a few additional options that specify pipe name or the hostname and port through which the external process will communicate with the LibreOfficeDev component process.
Open the your operating system's command prompt, navigate to the program folder of your LibreOfficeDev installation directory and type either:
flatpak run org.libreOffice.LibreOffice accept='socket,host=localhost,port=2021;urp;'
Either command above will start LibreOfficeDev with a communication channel open so that other processes can exchange messages with it.
Note that the previous example opens LibreOfficeDev start center. If you want to open a specific component, for instance Writer, you can add the --writer flag to the command, as follows.
Take note of the name, or host and port parameters, which in this example are aPipeName, or localhost and 2021, respectively.
Running an External Python Shell
Start the Python shell from within the program folder inside your LibreOfficeDev installation path. Follow the steps above to learn how to find your installation path.
On Linux or macOS:
$ cd /usr/lib/libreoffice/program
$ python
On Windows:
$ cd C:\\Program Files\\LibreOffice\\program\
$ python.exe
This will open the Python shell and now you can start typing commands that will be executed by LibreOfficeDev. But first you need to set up the pipe or the socket connection. The ScriptForge() statement below must precede the very first call to CreateScriptService().
Run either:
from scriptforge import ScriptForge, CreateScriptService
ScriptForge(pipe='aPipeName')
from scriptforge import ScriptForge, CreateScriptService
ScriptForge(hostname='localhost', port=2021)
Read the section Setting PYTHONPATH below in case of errors importing scriptforge.py or uno.py.
The second line of code above defines the pipe or host and port settings so that the Python shell can communicate with an ongoing LibreOfficeDev process opened with the same pipe or socket settings.
Now you can run other Python commands and they will be able to communicate with the LibreOfficeDev process. For example:
ui = CreateScriptService("UI")
bas = CreateScriptService("Basic")
doc = ui.OpenDocument("~/Documents/myFile.ods")
bas.MsgBox(doc.DocumentType)
Setting PYTHONPATH
Depending on your operating system's configuration you will need to set the environment variable PYTHONPATH in order to import the scriptforge.py library, which in turn requires importing the uno.py library.
Use your operating system's file search tool to determine the directory where both these files are located.
For instance, on a default Ubuntu installation both files may be located at:
scriptforge.py: Located in /usr/lib/libreoffice/program
uno.py: Located in /usr/lib/python3/dist-packages
In this case, set the environment variable PYTHONPATH as follows before starting the Python interpreter: