Programação com scripts Python

A Python macro is a function within a .py file, identified as a module. Unlike LibreOffice Basic and its dozen of UNO objects functions or services, Python macros use the XSCRIPTCONTEXT UNO single object, shared with JavaScript and BeanShell. The g_exportedScripts global tuple explicitly lists selectable macros from a module. Python modules hold autonomous code logic, and are independent from one another.

Variável global XSCRIPTCONTEXT

Genuine Basic UNO facilities can be inferred from XSCRIPTCONTEXT global variable. Refer to LibreOffice API for a complete description of XSCRIPTCONTEXT. XSCRIPTCONTEXT methods summarize as:

Métodos

Descrição

Mapeado no Basic como

getDocument()

A referência ao documento no qual o script pode operar.

ThisComponent

getDesktop()

A referência ao ambiente de trabalho no qual o script pode operar.

StarDesktop

getComponentContext()

O contexto do componente que o script pode usar para criar outros componentes UNO.

GetDefaultContext


HelloWorld and Capitalise installation shared scripts illustrate UNO-related macros making use of XSCRIPTCONTEXT global variable.

tip

Python standard output file is not available when running Python macros from Tools - Macros - Run Macro menu. Refer to Input/Output to Screen for more information.


Importação de módulos

warning

""" Carregador da biblioteca Python e importador de módulos


LibreOffice Basic libraries contain classes, routines and variables, Python modules contain classes, functions and variables. Common pieces of reusable Python or UNO features must be stored in My macros within (User Profile)/Scripts/python/pythonpath. Python libraries help organize modules in order to prevent module name collisions. Import uno.py inside shared modules.

Genuine BASIC UNO facilities can be inferred using uno.py module. Use Python interactive shell to get a complete module description using dir() and help() Python commands.

Funções

Descrição

Mapeado no Basic como

absolutize()

Devolve um URL de ficheiro absoluto a partir dos URLs fornecidos.

createUnoStruct()

Cria uma estrutura ou exceção UNO dada por typeName.

CreateUNOStruct()

fileUrlToSystemPath()

Devolve um caminho do sistema.

ConvertFromURL()

getClass()

Devolve a classe de uma exceção concreta, struct ou interface UNO.

getComponentContext()

Returns the UNO component context used to initialize the Python runtime.

GetDefaultContext()

Enum()

getConstantByName()

Looks up the value of an IDL constant by giving its explicit name.

Consultar grupos de constantes da API

isInterface()

Devolve Verdadeiro, quando obj é uma classe de uma interface UNO.

systemPathToFileUrl()

Devolve um URL de arquivo para o caminho do sistema especificado.

ConvertToURL()


Os scripts partilhados de instalação LibreLogo e TableSample usam o módulo uno.py.

Mais exemplos de Python-Basic

Python UNO

# O seu código começa a partir daqui

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

obj = smgr.createInstanceWithContext( .. , ctx)

CreateUnoService()

See Opening a Dialog

CreateUnoDialog()

See Creating a Listener

CreateUnoListener()

Consultar tipos de dados UNO

CreateUnoValue()

CreateObject()

EqualUnoObjects()

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

GetProcessServiceManager()

def hasUnoInterfaces(obj, *interfaces):

return set(interfaces).issubset(t.typeName for t in obj.Types)

HasUnoInterfaces()

IsUnoStruct()

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

DESK = 'com.sun.star.frame.Desktop'

desktop = smgr.createInstanceWithContext(DESK , ctx)

StarDesktop

desktop = smgr.createInstanceWithContext(DESK , ctx)

doc = desktop.CurrentComponent

ThisComponent


Importar um módulo incorporado

Similarly to LibreOffice Basic that supports browsing and dynamic loading of libraries, Python libraries can be explored and imported on demand. For more information on library containers, visit LibreOffice Application Programming Interface (API) or download LibreOffice Software Development Kit (SDK).

Importing a Python document embedded module is illustrated below, exception handling is not detailed:


            import uno, sys
            
            def load_library(library_name: str, module_name=None):
                """ load library and import module
                
                Adaptado de 'Bibliothèque de fonctions' de Hubert Lambert
                em https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213""" 
                doc = XSCRIPTCONTEXT.getDocument()  # document atual
                url = uno.fileUrlToSystemPath( \
                    '{}/{}'.format(doc.URL, 'Scripts/python'+library_name))  # ConvertToURL()
                if not url in sys.path:  # adicionar o caminho se necessário
                    sys.path.insert(0, url)  # doclib tem precedência
                if module_name:  # importar se for pedido
                    return zipimport.zipimporter(url).load_module(module_name)
            
            def import_embedded_python():
                ui = load_library("my_gui",'screen_io')  # adicionar caminho de <lib> + importar <module> 
                ui.MsgBox(sys.modules.keys())
            
            g_exportedScripts = (import_embedded_python,)  # Public macros