Python Guide - Useful functions

From The Document Foundation Wiki
Jump to navigation Jump to search

Return to Index

Other languages:
English • ‎español • ‎italiano • ‎日本語

Useful functions

In many examples show in this guide, we can used one or more the next functions.

Create instances

import uno

CTX = uno.getComponentContext()
SM = CTX.getServiceManager()

def create_instance(name, with_context=False):
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
        instance = SM.createInstance(name)
    return instance

Get desktop

  • One way
import uno

desktop = XSCRIPTCONTEXT.getDesktop()
  • Create instance
desktop = create_instance('', True)
  • Better for called from others macros
def get_desktop():
    return create_instance('', True)

Call dispatch

  • Many functions of LibreOffice, only can execute with dispatch
def call_dispatch(doc, url, args=()):
    frame = doc.getCurrentController().getFrame()
    dispatch = create_instance('')
    dispatch.executeDispatch(frame, url, '', 0, args)
  • For example, command copy
    doc = XSCRIPTCONTEXT.getDocument()
    call_dispatch(doc, '.uno:Copy')


from import MessageBoxButtons as MSG_BUTTONS

def msgbox(message, title='LibreOffice', buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'):
    """ Create message box
        type_msg: infobox, warningbox, errorbox, querybox, messbox
    toolkit = create_instance('')
    parent = toolkit.getDesktopWindow()
    mb = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message))
    return mb.execute()

Execute in other thread

import threading

def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        return t
    return run
  • Now, you can execute any macro in other thread
def main():


Dictionary to properties

1from import PropertyValue
3def dict_to_property(values, uno_any=False):
4    ps = tuple([PropertyValue(Name=n, Value=v) for n, v in values.items()])
5    if uno_any:
6        ps = uno.Any('[]', ps)
7    return ps

Get color

1def get_color(red, green, blue):
2    color = (red << 16) + (green << 8) + blue
3    return color