The ScriptForge library is available both for Basic and Python. Most services, methods and properties work identically in both programming languages. However, due to differences in how each language works, ScriptForge users must be aware of some characteristics of the library when using Python:
Methods and Property names: In Python, all methods and properties can be used in lowercased, ProperCased or camelCased formats.
Arguments: All keyword arguments passed on to methods are lowercased.
Dates: All date objects are passed and returned as datetime.datetime native Python objects.
Arrays: One-dimensional arrays are passed and returned as tuples (which is an immutable object). Two-dimensional arrays are passed and returned as tuples of tuples.
None: Python's None keyword is equivalent to Basic's Null, Empty or Nothing.
UNO objects: All UNO structures are exchanged between Basic and Python without any changes.
Debugging: Whenever an error occurs in Python scripts that use ScriptForge, the error message provided by the Python execution stack displays the line of code that triggered the error. In Basic error messages do not display this information.
Python typing hints - relating to ScriptForge services public methods and properties - can be obtained from IDEs that support such facility. Visually, while editing a user script:
hovering an object instance, a method or a property displays its detailed description.
a "." after an object instance displays a drop-down box listing all available interfaces.
brackets after a method-name start code-completion by displaying its arguments.
Typing hints are displayed when editing methods and properties with propercase letters.
Running Python scripts on LibreOfficeDev
Dependendo do que pretende alcançar, pode optar por uma das seguintes abordagens para executar scripts Python no LibreOfficeDev:
Executar scripts no processo atual do LibreOfficeDev: Os scripts Python são executados a partir do processo do LibreOfficeDev através do menu Ferramentas - Macros - Executar Macro ou da extensão APSO para chamar scripts do utilizador armazenados na pasta de scripts Python. Também é possível utilizar o shell Python do APSO para executar scripts Python de forma interativa.
Executar scripts separadamente do processo LibreOfficeDev: Os scripts Python são executados a partir de um processo externo que se liga a um processo LibreOfficeDev em execução através de um pipe ou de um socket.
Se pretender executar scripts a partir do processo LibreOfficeDev, recomenda-se instalar a extensão APSO (Alternative Script Organizer for Python). No entanto, para desenvolver scripts Python a partir do exterior do LibreOfficeDev, pode escolher o seu IDE Python preferido.
Executar scripts a partir do processo LibreOfficeDev
Utilização da extensão APSO
A forma mais fácil de começar a utilizar scripts Python no LibreOfficeDev é instalar a extensão APSO. Após a instalação, abra qualquer componente do LibreOfficeDev e aceda a Ferramentas - Macros - Organizar scripts Python.
In APSO's main window go to Menu - Python Shell.
Em alternativa, pode abrir o APSO utilizando o atalho predefinido Alt + Shift + F11.
Agora pode começar a escrever comandos Python e o shell irá apresentar o resultado correspondente após a execução de cada linha de código.
Para começar a utilizar a biblioteca ScriptForge, é necessário importar o método CreateScriptService, com o qual poderá aceder aos serviços fornecidos pela biblioteca. O exemplo abaixo utiliza o serviço Basic para apresentar uma caixa de mensagem.
from scriptforge import CreateScriptService
bas = CreateScriptService("Basic")
bas.MsgBox("Hello!")
Para executar o exemplo acima, introduza cada linha no shell do Python, uma a uma, premindo a tecla Enter após escrever cada linha de código.
Agora já pode começar a executar comandos Python utilizando qualquer um dos serviços do ScriptForge. Por exemplo, o trecho de código abaixo utiliza o serviço UI para criar um documento em branco no Writer.
Pode criar os seus próprios ficheiros Python e editá-los com o seu editor de texto preferido. Posteriormente, poderá chamá-los a partir de qualquer componente LibreOfficeDev.
Agora pode criar um ficheiro de texto na pasta de scripts do utilizador do Python, por exemplo, my_script.py, e começar a escrever os seus scripts.
A seguir, apresentamos um exemplo simples que obtém o valor numérico de uma célula do Calc e o incrementa em 1. Basta digitar o código seguinte no ficheiro my_script.py.
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, )
Este exemplo cria a função increment_cell. Note-se que g_exportedScripts é uma tupla que indica quais as funções que serão apresentadas no LibreOfficeDev como scripts do utilizador.
Para executar este script a partir de um documento do Calc:
Crie ou abra um ficheiro do Calc.
Introduza um valor numérico na célula «A1» da folha atual.
Vá a Ferramentas - Macros - Executar macros .
Selecione As minhas macros - my_script no seletor da biblioteca. Em seguida, selecione a função increment_cell na lista Nome da macro.
Clique em Executar. Repare que o valor na célula «A1» aumentou em 1.
Também pode utilizar o APSO para executar scripts Python de forma semelhante:
Primeiro, abra o APSO acedendo a Ferramentas - Macros - Organizar Scripts Python.
Na lista de macros, aceda a As minhas macros - my_script - increment_cell.
Clique em Executar.
Executar scripts separadamente do processo LibreOfficeDev
Determinar o caminho de instalação
O primeiro passo para executar scripts a partir de um processo separado é localizar a pasta onde o LibreOfficeDev está instalado. Existem várias formas de o fazer, mas o ScriptForge oferece uma forma rápida de identificar o caminho de instalação. Para tal, abra o shell Python do APSO e escreva:
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: