I’ve been having endless problems trying to get my Python macro to work reliably and I’m starting to think that my LibreOffice Python is corrupt. Here’s what’s happening:
-
Most LO libraries fail to import. Anything from “com.sun.star.awt.” always fails - uno and msgbox work for a while and then seem to randomly stop working. In PyCharm and Visual Studio the import statements sometimes show errors (either saying the import couldn’t be resolved or the module was not found) and sometimes they don’t.
-
Most crucially, ThisComponent and XSCRIPTCONTEXT do not work reliably. They were working yesterday and then without making any changes to my script, they suddenly started returning null today.
This is incredibly perplexing behavior, and it only happens with LibreOffice Python (other Python versions work 100% reliably). While trying to work my way through the labyrinth of Python documentation; I found this page: Python : Importing Modules which says that Python modules are stored in “(User Profile)/Scripts/python/pythonpath”; but I have no such folder.
I installed LibreOffice 7 yesterday which came with Python 3.8 and seemed to fix some of my issues. But upon opening my spreadsheet today, I find that my imports aren’t working again and my document reference is null. The script still runs, so the python installation is working to some degree.
I’m wondering if there is any definitive guide on how to set all of this up and if anyone can confirm that modules are stored in “(User Profile)/Scripts/python/pythonpath”. If so, how can I repair my LO Python? Updating LO clearly didn’t work. Maybe someone can upload the modules for me?
Here is my Basic code:
function cev(a as String) as double
Dim scriptPro As Object, myScript As Object
Dim a1(1), b1(0), c1(0) as variant
a1(0) = ThisComponent
a1(1) = a
scriptPro = ThisComponent.getScriptProvider()
myScript = scriptPro.getScript( _
"vnd.sun.star.script:Cell_Functions.py$calcEffectValue?language=Python&location=user")
cev = myScript.invoke(a1, b1, c1)
end function
And the relevant Python code:
def calcEffectValue(doc, effects):
nameDict = {}
#doc = XSCRIPTCONTEXT.getDocument()
# Populate dictionary with named ranges - ["name"] = value:
for range in doc.NamedRanges:
nameDict[range.getName()] = range.getReferredCells().getDataArray()[0][0]
This code fails because “doc” is null. This happens regardless of whether I rely on the reference passed in by the basic script or if I use XSCRIPTCONTEXT.getDocument() (which also sometimes shows an error in my IDEs, sometimes not).
This is happening with:
Windows 11
LibreOffice 7.4.5.1 with the included Python 3.8.16
PyCharm 2019.3
Visual Studio 2019 v16.11.23
This Python script is critical to an important project I’m working on. I’ve spent countless hours troubleshooting these issues and would love to find a permanent solution. Any help is appreciated.