Creating Python Scripts with ScriptForge

Differences between Basic and Python

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:

Ícone da dica

Visit LibreOfficeDev Python Scripts Help for more information on Python scripting using LibreOfficeDev.


Editing Python scripts in IDEs

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:

Ícone de nota

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:

Ícone da dica

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.

Ícone da dica

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.


        ui = CreateScriptService("UI")
        doc = ui.CreateDocument("Writer")
        

Criação de ficheiros de script em Python

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.

O primeiro passo é localizar onde os seus scripts de utilizador estão armazenados. Para tal, consulte a página de ajuda Organização e localização dos scripts Python.

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:

  1. Crie ou abra um ficheiro do Calc.

  2. Introduza um valor numérico na célula «A1» da folha atual.

  3. Vá a Ferramentas - Macros - Executar macros .

  4. Selecione As minhas macros - my_script no seletor da biblioteca. Em seguida, selecione a função increment_cell na lista Nome da macro.

  5. 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:

  1. Primeiro, abra o APSO acedendo a Ferramentas - Macros - Organizar Scripts Python.

  2. Na lista de macros, aceda a As minhas macros - my_script - increment_cell.

  3. 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:


      from scriptforge import CreateScriptService
      fs = CreateScriptService("FileSystem")
      fs.FileNaming = "SYS"
      inst_dir = fs.InstallFolder
      print(inst_dir)
      

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:

On Linux or macOS:

libreoffice --accept='pipe,name=aPipeName;urp;'

On Windows:

soffice.exe --accept='socket,host=localhost,port=2021;urp;'

as a Flatpak:

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.

./soffice --writer --accept='socket,host=localhost,port=2021;urp;'

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)
  
Ícone de nota

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:

In this case, set the environment variable PYTHONPATH as follows before starting the Python interpreter:

export PYTHONPATH=/usr/lib/libreoffice/program:/usr/lib/python3/dist-packages

Ícone de nota

The location of these files will be different for each operating system and LibreOfficeDev installation method.


Necessitamos da sua ajuda!

Necessitamos da sua ajuda!