Creating Python Scripts with ScriptForge

Diferencias entre BASIC y Python

La biblioteca ScriptForge está disponible tanto para BASIC como para Python. La mayor parte de los servicios, los métodos y las propiedades actúan de idéntica manera en ambos lenguajes de programación. Sin embargo, debido a diferencias de funcionamiento entre ambos, los usuarios de ScriptForge deben estar al tanto de ciertas características de la biblioteca cuando se utiliza Python:

tip

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


Ejecutar secuencias Python en ZetaOffice

Depending on what you intend to achieve, you may choose one of the following approaches to running Python scripts in ZetaOffice:

tip

If you plan to run scripts from inside the ZetaOffice process, it is recommended to install the APSO (Alternative Script Organizer for Python) extension. However, to develop Python scripts from outside ZetaOffice, you can choose your preferred Python IDE.


Ejecutar secuencias dentro del proceso de ZetaOffice

Utilizar la extensión APSO

The easiest way to get started with Python scripting in ZetaOffice is by installing the APSO extension. After installing it, open any ZetaOffice component and go to Tools - Macros - Organize Python Scripts.

In APSO's main window go to Menu - Python Shell.

tip

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.


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

Crear archivos de secuencia de órdenes de Python

Puede crear sus propios archivos Python y modificarlos con su editor de texto predilecto. Después, puede llamarlos desde cualquier componente de ZetaOffice.

El primer paso consiste en encontrar la ubicación de las secuencias de órdenes de usuario. Para hacerlo, consulte la página de ayuda Organización y ubicación de secuencias de órdenes Python.

Now you can create a text file inside your Python user scripts folder, for instance sf_test.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 the sf_test.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 ZetaOffice as user scripts.

Para ejecutar esta secuencia desde un documento de Calc:

  1. Cree o abra un archivo de Calc.

  2. Enter some numeric value into cell "A1" in the current sheet.

  3. Diríjase a Herramientas ▸ Macros ▸ Ejecutar macros.

  4. Choose My Macros - sf_test in the library selector. Then choose the increment_cell function under the Macro Name list.

  5. Pulse en Run (‘Ejecutar’). Observe cómo el valor de la celda A1 aumenta en una unidad.

También puede utilizar APSO para ejecutar secuencias escritas en Python de manera semejante:

  1. Primeramente, abra APSO yendo a Herramientas ▸ Macros ▸ Organizar secuencias de Python.

  2. En la lista de macros, navegue a Mis macros ▸ sf_test ▸ increment_cell.

  3. Pulse en Ejecutar.

Ejecutar secuencias separadamente del proceso de ZetaOffice

Determinar la ruta de la instalación

The first step to run scripts from a separate process is to find the folder where ZetaOffice 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:


    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 ZetaOffice 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 ZetaOffice with socket settings

Para ejecutar las secuencias Python desde un proceso separado, es necesario iniciar ZetaOffice con algunas opciones adicionales que especifican el nombre de anfitrión y el puerto a través del cual el proceso externo se comunicará con el proceso del componente de ZetaOffice.

Open the your operating system's command prompt, navigate to the program folder of your ZetaOffice installation directory and type:

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

La orden anterior iniciará ZetaOffice con una vía de comunicación abierta para que otros procesos puedan intercambiar mensajes con este.

Observe que el ejemplo anterior abre el centro de bienvenida de ZetaOffice. Si quiere abrir un componente en concreto, como por ejemplo Writer, puede añadir la opción --writer a la orden, como se ejemplifica a continuación:

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

Tome nota de los parámetros host y port, los cuales en este ejemplo son localhost y 2021, respectivamente.

Ejecutar un intérprete de Python externo

Start the Python shell from within the program folder inside your ZetaOffice installation path. Follow the steps above to learn how to find your installation path.

On Linux / Mac OS:

$ cd /usr/lib/libreoffice/program

$ python

En 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 ZetaOffice. But first you need to set up the socket connection.


    from scriptforge import ScriptForge, CreateScriptService
    ScriptForge(hostname='localhost', port=2021)
  
note

Read the section Setting PYTHONPATH below in case of errors importing scriptforge.py or uno.py.


The second line of code above defines the host and port settings so that the Python shell can communicate with an ongoing ZetaOffice process opened with the same socket settings.

Now you can run other Python commands and they will be able to communicate with the ZetaOffice 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

note

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