Options
There are a couple of was to accomplish this.
Using PIP
One way is to use an extension such as Extension for install and admin Python Pip in LibreOffice.
This will allow you to install pip package in LibreOffice.
Create a virtual environment
Another way to to create a virtual environment and use a python package such as OOO Development Tools (OooDev) , which I personally recommend, to automate connecting to LibreOffice and running your script.
Setting up Virtual Environment for LibreOffice and Python
In order to use python in a virtual environment with LibreOffice the approach is different depending on the operating system.
In any case the virtual environment needs to have access to uno.py
In Linux this seems simpler to accomplish then windows.
I wrote a guide for OOO Development Tools OooDev
because this is a somewhat of a complex process. The guide is part of the Dev Doc.
OOOENV
I also wrote a tool OOOENV to aid in managing uno
and virtual environments.
Using OooEnv
makes it easier to toggle or link to uno.py
will still allowing all the advantages of using a virtual environment.
Windows
In Windows the env
must point to the LO python environment. This is tricky but OooEnv
makes it simple.
The following command in the terminal:
(.venv) PS C:\python_ooo_dev_tools> oooenv env -t
results in the virtual environment being toggled from the original environment to an environment that points to LO python environment.
You should see output in the terminal similar to the following.
Set to UNO Environment
or
Set to Original Environment
oooenv env -t
is a toggle it switches back and forth between original and uno
environment.
For running LibreOffice then environment would need to be set to uno
.
For running poetry
or pip
commands the environment would need to be set to original
.
Linux/Mac
Linux and Mac (although I have not yet tested Mac) are much more simple. A link from LibreOffice uno.py
into the virtual environment is usually all that is needed. Although if LibreOffice is updated then it may be necessary to create link again.
The following command in the terminal:
(.venv) $ oooenv cmd-link --add
Will create the links in the virtual environment.
Once the links are created everything else is as expected. No need to toggle environment like Windows requires.
Summary
Once all of that is done you should have a working Virtual Environment. With packages such as the OooDev
project it super simple to run python scripts for LibreOffice.
Example of starting LibreOffice with just a few lines of code using OooDev
.
loader = Lo.load_office(Lo.ConnectSocket())
doc = Calc.open_doc(fnm=self._fnm)
GUI.set_visible(is_visible=True)
There are many examples of this in the LibreOffice Python UNO Examples repository.
It basically only take a few lines of code to start LibreOffice.
For an example python project starting LibreOffice and using OooEnv
see: Build Table
Full Disclaimer. I am the lead author of OooDev
, OooEnv
and the UNO Examples
.