Macros/Python Guide/Calling Python from Basic

    From The Document Foundation Wiki

    ⇐ Return to Index


    Let's say you have a Python script in the user specific script directory, as mentioned in the Introduction:

    On Linux, it would be /home/USER/.config/libreoffice/4/user/Scripts/python. Contents of a file named utcNow.py in that directory:

    from datetime import datetime
    
    def utcNow():
        return datetime.utcnow().strftime("%Y-%m-%d %H:%M")
    
    g_exportedScripts = (utcNow,)

    Now, you'd like to use this function from Basic. You can open Tools ▸ Macros ▸ Organize Macros ▸ Basic..., select your document, make a new module, select it and choose "Edit". Then you can enter:

    Function UtcNow
    oScriptProvider = ThisComponent.getScriptProvider()
    oScript = oScriptProvider.getScript("vnd.sun.star.script:utcNow.py$utcNow?language=Python&location=user")
    UtcNow = oScript.invoke(array(), array(), array())
    End Function

    The function UtcNow returns the Basic string that is returned by the Python function. Note how the call to getScript specifies the file name of the Python script, the function name (not necessarily the same!) and the location (user). Other settings possible are in the Scripting Framework URI Specification.

    If you can't make Basic find the script, try running LibreOffice with the environment variables PYSCRIPT_LOG_LEVEL=DEBUG PYSCRIPT_LOG_STDOUT=1. That way, you'll see where LibreOffice is looking.

    ⇐ Return to Index