Search code examples
pythonlibreoffice-calc

how to run libreoffice python script using scriptforge


I am trying to organize my python project that currently only adds a menu to a libreoffice calc menu bar:

# this file is called AddMenu.py which is located in 'C:\Program Files\LibreOffice\share\Scripts\python'

def create_menu(args=None):
   o_doc = CreateScriptService("Document")
   o_menu = o_doc.CreateMenu("Test Menu")
   o_menu.AddItem("About", command="About")
   o_menu.AddItem("Testing",
                 script="vnd.sun.star.script:AddMenu.py$item_b_listener?language=Python&location=user")

def item_b_listener(args):
    bas = CreateScriptService("Basic")
    s_args = args.split(",")
    msg = f"Menu name: {s_args[0]}\n"
    msg += f"Menu item: {s_args[1]}\n"
    msg += f"Item ID: {s_args[2]}\n"
    msg += f"Item status: {s_args[3]}"
    bas.MsgBox(msg)

The menu and buttons are added as expected, and About works fine. However, when I click on the "Test Menu" I get an error:

Library :   ScriptForge
Service :   Session
Method :    ExecutePythonScript
Arguments: [Scope], Script, arg0[, arg1] ...


A serious error has been detected in your code on argument : « Script ».

The requested Python script could not be located in the given libraries and modules.
« Scope » = user
« Script » = AddMenu.py$item_b_listener


THE EXECUTION IS CANCELLED.

Do you want to receive more information about the 'ExecutePythonScript' method ?

Any suggestions?

Follow up question: how do I run a python script when calc starts? Since the menu doesn't persist on restarting calc, I need to run the macro to reinstall it


Solution

  • &location=user

    That indicates the LibreOffice user profile directory, for example C:\Users\(your username)\AppData\Roaming\LibreOffice\4\user\Scripts\python.

    So either change that part to &location=application or move the script to the user profile directory.

    https://help.libreoffice.org/latest/sq/text/sbasic/python/python_locations.html