Creating Python Scripts with ScriptForge

Differences between Basic and Python

A ScriptForge programkönyvtár elérhető Basic és Python nyelven is. A legtöbb szolgáltatás, metódus és tulajdonság azonos módon működik mindkét programozási nyelven. Az egyes nyelvek működésének különbségei miatt azonban a ScriptForge felhasználóknak tisztában kell lenniük a programkönyvtár néhány jellemzőjével, ha Python nyelvet használnak:

tip

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


Running Python scripts on LibreOffice

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

tip

Ha a LibreOffice folyamaton belülről tervez parancsfájlokat futtatni, ajánlott telepíteni a APSO (Alternative Script Organizer for Python) bővítményt. A Python parancsfájlok LibreOffice folyamaton kívülről történő fejlesztéséhez azonban kiválaszthatja az Ön által preferált Python IDE-t.


Running Scripts from inside the LibreOffice process

Using the APSO extension

A legegyszerűbben az APSO bővítmény telepítésével kezdheti el a Python parancsfájlok írását a LibreOffice programban. Telepítése után nyissa meg bármelyik LibreOffice komponenst, és használja az Eszközök - Makrók - Python parancsfájlok rendezése menüparancsot.

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.

A ScriptForge könyvtár használatának megkezdéséhez importálnunk kell a CreateScriptService metódust, amellyel hozzáférhetünk a könyvtár által nyújtott szolgáltatásokhoz. Az alábbi példa a Basic szolgáltatást használja egy üzenetmező megjelenítésére.


    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")
  

Creating Python script files

You can create your own Python files and edit them with your preferred text editor. Later you can call them from within any LibreOffice 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 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 LibreOffice as user scripts.

To run this script from within a Calc document:

  1. Create or open a Calc file.

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

  3. Go to Tools - Macros - Run Macros .

  4. Choose My Macros - sf_test 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 - sf_test - increment_cell.

  3. Kattintson a Végrehajtás gombra.

Running Scripts separately from the LibreOffice process

Determining the Installation Path

A parancsfájlok különálló folyamatból történő futtatásának első lépése, hogy megkeresse azt a mappát, ahová a LibreOffice telepítve van. Ennek több módja is van, de a ScriptForge egy gyors módszert kínál a telepítési útvonal azonosítására. Ehhez nyissa meg az APSO Python héját, és írja be a következőt:


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

A fenti kód kimenete az alapkönyvtár, ahová a LibreOffice telepítve van. Most hozzá kell adnia a "program" almappát a kapott elérési útvonalhoz. Ez az az alapmappa, ahonnan a Python parancsfájlokat egy külön folyamatból fogja futtatni.

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

A Python-parancsfájlok különálló folyamatból történő futtatásához el kell indítania a LibreOffice programot néhány további opcióval, amelyek megadják azt a gépnevet és portot, amelyen keresztül a külső folyamat kommunikálni fog a LibreOffice komponensfolyamatával.

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

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

The command above will start LibreOffice with a communication channel open so that other processes can exchange messages with it.

Note that the previous example opens LibreOffice 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 host and port parameters, which in this example are localhost and 2021, respectively.

Running an External Python Shell

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

On Linux / Mac OS:

$ cd /usr/lib/libreoffice/program

$ python

Windowson:

$ 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 LibreOffice. 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 LibreOffice process opened with the same socket settings.

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


Támogasson minket!