A (Libre/Open)Office Python macro looks like:
Code: Select all
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,
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
IDE_utils module innocuously integrates in Python macros with the following features:
- start, connect, adapt, run and stop steps are optional
- Support multiple platforms i.e. essentially Linux, MacOS and Windows
- on-demand startup --options
- Permit pipe and/or socket connections
- decoupled coding using Inversion of Control
- Provide Service pooling, context pooling
- and KISS
Code: Select all
#! # IDE_utils.py
import officehelper
RUNNERS = 'Runners.json'
class Runner(json=None): pass
class ScriptContext(): pass
_ctx = officehelper.bootstrap()
XSCRIPTCONTEXT = ScriptContext(_ctx)
def connect(host='localhost', port=2002, pipe=None): pass
def start(): pass
def stop(): pass
Code: Select all
import uno
def macro_1(): pass # Your code goes here
def macro_2(): pass # Your code goes here
g_exportedScripts = macro_1, macro_2 # *Office public macros
#! EXAMPLE 1
if __name__ == "__main__":
''' LibreOffice as a Service IDE runnable code'''
import IDE_utils as geany
with geany.Runner() as jesse_owens: # Start/Stop
XSCRIPTCONTEXT = geany.XSCRIPTCONTEXT # Connect/Adapt
macro_2() # Run
Code: Select all
#! EXAMPLE 2
if __name__ == "__main__":
import IDE_utils as pycharm
with pycharm.Runner(json={pgm: [*options]}) as carl_lewis: # Start/Stop
ctx = pycharm.connect(pipe='LibreOffice')
XSCRIPTCONTEXT = pycharm.ScriptContext(ctx) # Adapt
macro_1() # Run
Note: A default injection is performed, in the background, with last pgm-options(ii) pair, and overrides officehelper bootstraping.
Code: Select all
#! EXAMPLE 3
if __name__ == "__main__":
import IDE_utils as usain_bolt # Runner()
usain_bolt.start()
ctx = usain_bolt.connect()
XSCRIPTCONTEXT = usain_bolt.ScriptContext(ctx) # Adapt
pass # Your code goes here
usain_bolt.stop()
Usage:
- Copy this module into your <OFFICE>/program/ directory OR Include it into your IDE project directory
- Include one of the examples into your Python macro
- Run your (Libre|Open) macro from your preferred IDE
Notes:
- officehelper is a LibreOffice and OpenOffice standard module
- {pgm: [*options]} syntax is described in Services Specification