- Macros/Python Basics
- Useful LibreOffice Packages
- IDE Project Setup
- Geany
- Pyzo
- PyCharm
- What’s in a Macro
- Start, Connect, Adapt, Run & Stop
- IDE enablement
- Recommended Use
- Введение
- Установка
- Поддержка тестов для макросов Python
- Где хранятся макросы?
- Каталог с профилем пользователя, макросы доступны только для пользователя
- Profile USER folder, macros available only for USER
- Каталог LibreOffice, макросы доступны для всех пользователей
- Внутри документа
- Macros/Python Basics
- Useful LibreOffice Packages
- IDE Project Setup
- Geany
- Pyzo
- PyCharm
- What’s in a Macro
- Start, Connect, Adapt, Run & Stop
- IDE enablement
- Recommended Use
Macros/Python Basics
This page presents the steps enabling to develop LibreOffice Python macros within an Integrated Development Environment (IDE). Configuration or preferences setup are presented for a limited set of free and open source (FOSS) IDEs. Direct editing and debugging of Python macros within LibreOffice requires solely the Alternative Python Script Organizer (APSO) extension. In which case Start, Connect, & Stop chapter content can be skipped.
( . Documents, Configuration, Object Inspection . )
Useful LibreOffice Packages
For those wishing to explore cross-compatibility:
IDE Project Setup
Each IDE requires a different configuration or setup.
Geany
Libreoffice or OpenOffice embedded Python interpreters require to be defined explicity in Geany Projects — Properties — Build dialogs:
- MacOS
- P1. Compile = /Applications/LibreOffice.app/Contents/Resources/python -m py_compile «%f»
- E1. Execute = /Applications/LibreOffice.app/Contents/Resources/python «%f»
- P1. Compile = opt/openoffice4/program/python -m py_compile «%f»
- E1. Execute = opt/openoffice4/program/python «%f»
- Python commands
- 1. Compile = «D:\Program Files\LibreOffice 5\program\python» -m py_compile «%f»
- 2. Interpret = «D:\Program Files\LibreOffice 5\program\python»
- 1. Execute = «D:\Program Files\LibreOffice 5\program\python» «%f»
- 2. Unit Tests = «D:\Program Files\LibreOffice 5\program\python» -m unittest discover
Pyzo
Pyzo configuration dialog for embedded Python interpreters as of Shell — Edit shell configurations. menu:
PyCharm
LibreOffice Python interpreter configuration with PyCharm default settings dialog:
What’s in a Macro
A LibreOffice Python macro may look like:
import uno def my_1st_macro(): # Won't run directly in Anaconda, Geany, KDevelop, PyCharm or else doc = XSCRIPTCONTEXT.getDocument() doc.getText().setString("Hello World!") g_exportedScripts = my_1st_macro,
Executing the above requires bridging together the IDE and LibreOffice. Once done UNO objects become accessible.
Up to five steps can be necessary to achieve this:
- Start LibreOffice as a service
- Connect to a service
- create a XSCRIPTCONTEXT Adaptor
- Run the macro
- Stop LibreOffice as a service
While examples available on the internet do not resort to all these steps, their study exhibits coding guidelines that IDE_utils module borrows from in order to innocuously integrate in IDEs.
Start, Connect, Adapt, Run & Stop
The table below lists a few public (Libre/Open)Office Python macro examples. Their usage of the Start, Connect, Adapt, Run, Stop steps is indicated.
IDE enablement
Based on these resources, requirements for Python macro enablement in IDEs can be summarised as:
- start, connect, adapt, run and stop steps to be optional
- Support multiple platforms i.e. essentially Linux, MacOS and Windows
- on-demand startup —options
- Permit pipe and/or socket connections
- decoupled coding using injection
- Provide Service pooling, context pooling
- and KISS
IDE_utils module proposal: A Runner() context manager class is responsible for starting and stopping soffice instances. An optional Runners.json configuration file contains service-options pairs holding the services to start and their running conditions. A connect() function bridges the actual IDE and LibreOffice instances. A ScriptContext() object is injected as XSCRIPTCONTEXT built-in. start() and stop() coding facilities are wrapping-up Runner() features. The module skeleton looks like:
#! # IDE_utils.py import officehelper RUNNERS = 'Runners.json' class Runner(soffice=None): pass class ScriptContext(): pass _ctx = officehelper.bootstrap() XSCRIPTCONTEXT = ScriptContext(_ctx) def connect(host='localhost', port=2002, pipe=None): pass def start(soffice=None): pass def _stop(): pass
Recommended Use
import uno def my_1st_macro(): pass # Your code goes here g_exportedScripts = my_1st_macro, # Published macros if __name__ == '__main__': from IDE_utils import Runner, XSCRIPTCONTEXT with Runner() as jesse_owens: # Start/Stop, Connect/Adapt my_1st_macro # Run
The example above should be your preferred use for IDE_utils. As starting and stopping a service may not fit all situations, these steps are optional. That same module allows the customization of LibreOffice — or OpenOffice — services running conditions. «Getting Started» user guide provides detailed description of the 3 different ways to use IDE_utils:
- Resorting to (Libre/Open)Office default Python bootstrap() mechanism,
- Letting Runner() and ScriptContext() objects take responsibility for start, connect, adapt, run and stop steps,
- Deciding when to perform start, connect, adapt, run and stop steps.
Введение
LibreOffice позволяет пользователям писать макросы на различных интерпретируемых языках, один из которых Python. PyUNO — это компонент, который дает пользователям доступ к API LibreOffice из Python.
Установка
На некоторых операционных системах, таких, как Ubuntu 18.04 LTS вам нужно установить дополнительный пакет OS. В Ubuntu такой пакет называется libreoffice-script-provider-python и содержит такие файлы, как scriptproviderforpython.rdb (метаданные XML) и pythonscript.py (инфраструктура Python).
sudo apt install libreoffice-script-provider-python
Поддержка тестов для макросов Python
Откройте новый документ в Writer. Выберите пункт меню Сервис ▸ Макросыs ▸ Выполнить макрос. , откроется диалог «Выбор макроса». В списке «Библиотека» выберите Макросы LibreOffice ▸ HelloWorld , в списке «Имя макроса» выберите HelloWorldPython и нажмите кнопку Выполнить
Если вы видите этот результат, ваша система может выполнять макросы Python.
Где хранятся макросы?
Каталог с профилем пользователя, макросы доступны только для пользователя
/home/USER/.config/libreoffice/4/user/Scripts/python
%APPDATA%\LibreOffice\4\user\Scripts\python
~/Library/Application Support/LibreOffice/4/user/Scripts/python/
There is no built-in way to edit Python scripts so you have to use your own text editor. There are 3 places where you can put your code.
Profile USER folder, macros available only for USER
/home/USER/.config/libreoffice/4/user/Scripts/python
%APPDATA%\LibreOffice\4\user\Scripts\python
~/Library/Application Support/LibreOffice/4/user/Scripts/python/
Каталог LibreOffice, макросы доступны для всех пользователей
/usr/lib/libreoffice/share/Scripts/python/
/usr/lib/libreoffice/share/Scripts/python/
Это каталог по умолчанию, он может быть иным, если при установке был выбран иной каталог. Если каталог не существует, вы должны его создать с учётом заглавных символов.
Внутри документа
-
- Любой ODF файл — это в действительности ZIP-архив, который можно распаковать. В корне создайте каталог
myfile | . ├── META-INF │ └── manifest.xml ├── Scripts │ └── python │ └── mymacros.py .
- Отредактируйте файл manifest.xml в каталоге META-INF и добавьте строки, просто до закрывающего тэга
- Any ODF file, really is a ZIP file, you can extract this file like extract normally this type files. In the root, create folder
myfile | . ├── META-INF │ └── manifest.xml ├── Scripts │ └── python │ └── mymacros.py .
- Теперь, запакуйте каталог обратно. Внимание, не пакуйте внешний каталог, запакуйте только содержимое каталога.
Macros/Python Basics
This page presents the steps enabling to develop LibreOffice Python macros within an Integrated Development Environment (IDE). Configuration or preferences setup are presented for a limited set of free and open source (FOSS) IDEs. Direct editing and debugging of Python macros within LibreOffice requires solely the Alternative Python Script Organizer (APSO) extension. In which case Start, Connect, & Stop chapter content can be skipped.
( . Documents, Configuration, Object Inspection . )
Useful LibreOffice Packages
For those wishing to explore cross-compatibility:
IDE Project Setup
Each IDE requires a different configuration or setup.
Geany
Libreoffice or OpenOffice embedded Python interpreters require to be defined explicity in Geany Projects — Properties — Build dialogs:
- MacOS
- P1. Compile = /Applications/LibreOffice.app/Contents/Resources/python -m py_compile «%f»
- E1. Execute = /Applications/LibreOffice.app/Contents/Resources/python «%f»
- P1. Compile = opt/openoffice4/program/python -m py_compile «%f»
- E1. Execute = opt/openoffice4/program/python «%f»
- Python commands
- 1. Compile = «D:\Program Files\LibreOffice 5\program\python» -m py_compile «%f»
- 2. Interpret = «D:\Program Files\LibreOffice 5\program\python»
- 1. Execute = «D:\Program Files\LibreOffice 5\program\python» «%f»
- 2. Unit Tests = «D:\Program Files\LibreOffice 5\program\python» -m unittest discover
Pyzo
Pyzo configuration dialog for embedded Python interpreters as of Shell — Edit shell configurations. menu:
PyCharm
LibreOffice Python interpreter configuration with PyCharm default settings dialog:
What’s in a Macro
A LibreOffice Python macro may look like:
import uno def my_1st_macro(): # Won't run directly in Anaconda, Geany, KDevelop, PyCharm or else doc = XSCRIPTCONTEXT.getDocument() doc.getText().setString("Hello World!") g_exportedScripts = my_1st_macro,
Executing the above requires bridging together the IDE and LibreOffice. Once done UNO objects become accessible.
Up to five steps can be necessary to achieve this:
- Start LibreOffice as a service
- Connect to a service
- create a XSCRIPTCONTEXT Adaptor
- Run the macro
- Stop LibreOffice as a service
While examples available on the internet do not resort to all these steps, their study exhibits coding guidelines that IDE_utils module borrows from in order to innocuously integrate in IDEs.
Start, Connect, Adapt, Run & Stop
The table below lists a few public (Libre/Open)Office Python macro examples. Their usage of the Start, Connect, Adapt, Run, Stop steps is indicated.
IDE enablement
Based on these resources, requirements for Python macro enablement in IDEs can be summarised as:
- start, connect, adapt, run and stop steps to be optional
- Support multiple platforms i.e. essentially Linux, MacOS and Windows
- on-demand startup —options
- Permit pipe and/or socket connections
- decoupled coding using injection
- Provide Service pooling, context pooling
- and KISS
IDE_utils module proposal: A Runner() context manager class is responsible for starting and stopping soffice instances. An optional Runners.json configuration file contains service-options pairs holding the services to start and their running conditions. A connect() function bridges the actual IDE and LibreOffice instances. A ScriptContext() object is injected as XSCRIPTCONTEXT built-in. start() and stop() coding facilities are wrapping-up Runner() features. The module skeleton looks like:
#! # IDE_utils.py import officehelper RUNNERS = 'Runners.json' class Runner(soffice=None): pass class ScriptContext(): pass _ctx = officehelper.bootstrap() XSCRIPTCONTEXT = ScriptContext(_ctx) def connect(host='localhost', port=2002, pipe=None): pass def start(soffice=None): pass def _stop(): pass
Recommended Use
import uno def my_1st_macro(): pass # Your code goes here g_exportedScripts = my_1st_macro, # Published macros if __name__ == '__main__': from IDE_utils import Runner, XSCRIPTCONTEXT with Runner() as jesse_owens: # Start/Stop, Connect/Adapt my_1st_macro # Run
The example above should be your preferred use for IDE_utils. As starting and stopping a service may not fit all situations, these steps are optional. That same module allows the customization of LibreOffice — or OpenOffice — services running conditions. «Getting Started» user guide provides detailed description of the 3 different ways to use IDE_utils:
- Resorting to (Libre/Open)Office default Python bootstrap() mechanism,
- Letting Runner() and ScriptContext() objects take responsibility for start, connect, adapt, run and stop steps,
- Deciding when to perform start, connect, adapt, run and stop steps.