Text Documents (Writer)
HTML Documents (Writer Web)
Spreadsheets (Calc)
Presentations (Impress)
Drawings (Draw)
Database Functionality (Base)
Formulae (Math)
Charts and Diagrams
Macros and Scripting
Office Installation
Common Help Topics
OneOffice Logo

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:

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

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

Running Python scripts on Office

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

  • Run Scripts inside the current Office process: Python scripts are executed from within the Office process by using the Tools - Macros - Run Macro menu or the APSO extension to call user scripts stored in the Python scripts folder. You can also use the APSO Python shell to interactively run Python scripts.
  • Run Scripts separately from the Office process: Python scripts are executed from an external process that connects to an ongoing Office process using a socket.

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

Running Scripts from inside the Office process

Using the APSO extension

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

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

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

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 Office 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 Office 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 - Organise Python Scripts.

  2. In the macro list, navigate to My Macros - sf-test - increment-cell.

  3. Click Execute.

Running Scripts separately from the Office process

Determining the Installation Path

The first step to run scripts from a separate process is to find the folder where Office 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 Office 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 Office with socket settings

To run Python scripts from a separate process, you need to start Office with a few additional options that specify the hostname and port through which the external process will communicate with the Office component process.

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

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

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

Note that the previous example opens Office start centre. 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 Office installation path. Follow the steps above to learn how to find your installation path.

On Linux / Mac OS:

$ cd /usr/lib/libreoffice/program

$ python

On Windows:

$ cd C:\Program Files\Office\program\

$ python.exe

This will open the Python shell and now you can start typing commands that will be executed by Office. But first you need to set up the socket connection.


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

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

Now you can run other Python commands and they will be able to communicate with the Office process. For example:


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