Programming with Python Scripts

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.

Zmienna globalna 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:

Metody

Opis

Mapowane w Basic jako

getDocument()

Odwołanie do dokumentu, w którym może działać skrypt.

ThisComponent

getDesktop()

Odniesienie do pulpitu, na którym może działać skrypt.

StarDesktop

getComponentContext()

Kontekst komponentu, którego skrypt może użyć do tworzenia innych komponentów UNO.

GetDefaultContext


Wspólne skrypty instalacyjne HelloWorld i Capitalise ilustrują makra związane z UNO wykorzystujące zmienną globalną XSCRIPTCONTEXT.

tip

Standardowy plik wyjściowy Pythona nie jest dostępny podczas uruchamiania makr Pythona z menu Narzędzia - Makra - Uruchom makro. Zobacz Wejście i wyjście ekranu, aby uzyskać więcej informacji.


Import modułu

warning

Element XSCRIPTCONTEXT nie jest dostarczany do importowanych modułów.


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.

Funkcje

Opis

Mapowane w Basic jako

absolutize()

Zwraca bezwzględny adres URL pliku z podanych adresów URL.

createUnoStruct()

Tworzy strukturę UNO lub wyjątek określony przez typeName.

CreateUNOStruct()

fileUrlToSystemPath()

Zwraca ścieżkę systemową.

ConvertFromURL()

getClass()

Zwraca klasę konkretnego wyjątku UNO, struktury lub interfejsu.

getComponentContext()

Zwraca kontekst składnika UNO używany do inicjowania środowiska uruchomieniowego Pythona.

GetDefaultContext()

Enum()

getConstantByName()

Wyszukuje wartość stałej IDL, podając jej jawną nazwę.

Zobacz grupy stałych API

isInterface()

Zwraca True, gdy obj jest klasą interfejsu UNO.

systemPathToFileUrl()

Zwraca adres URL pliku dla podanej ścieżki systemowej.

ConvertToURL()


Współdzielone skrypty instalacyjne LibreLogo i TableSample używają modułu uno.py.

Więcej przykładów Python-Basic

UNO Pythona

Funkcje UNO Basic

ctx = uno.getComponentContext()

smgr = ctx.getServiceManager()

obj = smgr.createInstanceWithContext( .. , ctx)

CreateUnoService()

See Opening a Dialog

CreateUnoDialog()

See Creating a Listener

CreateUnoListener()

Zobacz typy danych 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


Importing an embedded Module

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):
                """ załaduj bibliotekę i moduł importu
                
                przystosowano z 'Bibliothèque de fonctions' autorstwa Huberta Lamberta
                pod adresem https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213"""
                doc = XSCRIPTCONTEXT.getDocument()  # bieżący dokument
                url = uno.fileUrlToSystemPath( \
                    '{}/{}'.format(doc.URL, 'Scripts/python'+library_name))  # ConvertToURL()
                if not url in sys.path:  # dodaj ścieżkę, jeśli to konieczne
                    sys.path.insert(0, url)  # doclib ma pierwszeństwo
                if module_name:  # importuj na żądanie
                    return zipimport.zipimporter(url).load_module(module_name)
            
            def import_embedded_python():
                ui = load_library("my_gui",'screen_io')  # dodaj ścieżkę  + import 
                ui.MsgBox(sys.modules.keys())
            
            g_exportedScripts = (import_embedded_python,)  # Public macros