Use static object in LibreOffce python script?

Question:

I’ve got a LibreOffice python script that uses serial IO. On my systems, opening a serial port is a very slow process (around 1 second), so I’d like to keep the serial port open, and just send stuff as required.

But LibreOffice python apparently reloads the python framework every time a call is made. Unlike most python implementations, where the process is persistent, and un-enclosed code in a module is run once, when the module is imported.

Is there a way in LibreOffice python to persist objects between calls?

SerialObject=None

def return_global():
  return str(SerialObject)  #always returns "None"

def init_serial_object():
  SerialObject=True
Asked By: david

||

Answers:

It looks like there is a simple bug. Add global and then it works.

However, it may be that the real problem is your setup. Here is a working example. Put the code in a file called inctest.py under $LIBREOFFICE_USER_DIR/Scripts/python/pythonpath/incmod/.

def init_serial_object():
    global SerialObject
    SerialObject=True

def moduleVersion():
    return "2.0"  #change to verify that this is the most recently updated code

The code to call it should be located in the user profile directory (that is, location=user).

from incmod import inctest
inctest.init_serial_object()
msgbox("{}: {}".format(
    inctest.moduleVersion(), inctest.return_global()))

Run the script by going to Tools > Macros > Run Macro and find it under My Macros.

Be aware that inctest.py will not always get reloaded. There are two ways to reload it: restart LibreOffice, or force python to reload it by doing del sys.modules[mod].

The moduleVersion() function is not necessary but helps you see when the module is getting reloaded — make changes to that line and then see whether the output changes.

Answered By: Jim K
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.