Ejecutar secuencias de órdenes Python para LibreOfficeDev

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

Icono de consejo

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


Ejecutar secuencias de órdenes dentro del proceso de LibreOfficeDev

Using the APSO extension

La forma más sencilla de empezar a utilizar secuencias de órdenes Python en LibreOfficeDev es instalando la extensión APSO. Una vez instalada, abra cualquier componente de LibreOfficeDev y diríjase a Herramientas ▸ Macros ▸ Organizar secuencias de Python.

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

Icono de consejo

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 secuencias de órdenes en Python

You can create your own Python files and edit them with your preferred text editor. Later you can call them from within any LibreOfficeDev component.

The first step is to locate where your user scripts are stored. For that, refer to Python Scripts Organization and Location help page.

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:

  1. Cree o abra un archivo de Calc.

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

  3. Vaya a Herramientas ▸ Macros ▸ Ejecutar macros.

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

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

  1. First open APSO by going to Tools - Macros - Organize Python Scripts.

  2. In the macro list, navigate to My Macros - my_script - increment_cell.

  3. Pulse en Ejecutar.

Ejecutar secuencias de órdenes separadas del proceso de LibreOfficeDev

Determinar la ruta de instalación

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:


      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.

Inicie LibreOfficeDev con configuraciones de pipe o socket

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 / Mac OS:

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

En 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.

Observe que el ejemplo anterior abre el centro de bienvenida de LibreOfficeDev. Si desea abrir un componente específico, por ejemplo Writer, puede añadir el parámetro --writer a la orden, tal y como se muestra a continuación.

./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.

Ejecutar un intérprete de órdenes Python externo

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 / 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 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)
  
Icono de nota

Lea la sección Configurar PYTHONPATH que aparece a continuación si se producen errores al importar scriptforge.py o uno.py.


El segundo renglón de código de más arriba define las configuraciones pipe o host y port para que el intérprete de Python pueda comunicarse con un proceso de LibreOfficeDev en ejecución que se haya abierto con los mismas configuraciones de canalización o «socket».

Ahora puede ejecutar otras órdenes de Python y estas podrán comunicarse con el proceso de LibreOfficeDev. Por ejemplo:


    ui = CreateScriptService("UI")
    bas = CreateScriptService("Basic")
    doc = ui.OpenDocument("~/Documents/myFile.ods")
    bas.MsgBox(doc.DocumentType)
  

Establecer PYTHONPATH

Dependiendo de la configuración de su sistema operativo, tendrá que establecer la variable de entorno PYTHONPATH para poder importar la biblioteca scriptforge.py, que a su vez requiere importar la biblioteca uno.py.

Sírvase de la herramienta de búsqueda del sistema operativo para determinar el directorio en que se encuentran ambos archivos.

Por ejemplo, en una instalación predeterminada de Ubuntu, ambos archivos pueden encontrarse en:

En este caso, establezca la variable de entorno PYTHONPATH de la siguiente manera antes de iniciar el intérprete de Python:

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

Icono de nota

La ubicación de estos archivos variará en función del sistema operativo y del método de instalación de LibreOfficeDev.


¡Necesitamos su ayuda!

¡Necesitamos su ayuda!