Довідка LibreOfficeDev 25.8
A Python macro is a function within a .py file, identified as a module. Unlike LibreOfficeDev 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.
Genuine Basic UNO facilities can be inferred from XSCRIPTCONTEXT global variable. Refer to LibreOfficeDev API for a complete description of XSCRIPTCONTEXT. XSCRIPTCONTEXT methods summarize as:
| Методи | Опис | Доступно в Basic як | 
|---|---|---|
| getDocument() | Посилання на документ, з яким може працювати сценарій. | ThisComponent | 
| getDesktop() | Посилання на стільницю, з якою може працювати сценарій. | StarDesktop | 
| getComponentContext() | Контекст компонента, який скрипт може використовувати для створення інших компонентів uno. | GetDefaultContext | 
Встановлені сценарії HelloWorld і Capitalise ілюструють створення макросів на основі UNO з використанням глобальної змінної XSCRIPTCONTEXT.
Стандартний вивідний файл Python недоступний при запуску макроса Python за допомогою меню . Детальніше див. Ввід/вивід на екран.
XSCRIPTCONTEXT не надається імпортованим модулям.
LibreOfficeDev 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.
| Функції | Опис | Доступно в Basic як | 
|---|---|---|
| absolutize() | Returns an absolute file url from the given urls. | |
| createUnoStruct() | Створює структуру UNO або виняток, заданий typeName. | CreateUNOStruct() | 
| fileUrlToSystemPath() | Повертає системний шлях. | ConvertFromURL() | 
| getClass() | Повертає клас конкретного винятку, структури чи інтерфейсу 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. | Див. групи констант API | 
| isInterface() | Повертає True, якщо obj є класом інтерфейсу UNO. | |
| systemPathToFileUrl() | Повертає URL файлу для даного системного шляху. | ConvertToURL() | 
LibreLogo, NamedRanges, SetCellColor and TableSample preinstalled scripts use uno.py module.
| Python UNO | Можливості Basic UNO | 
|---|---|
| ctx = uno.getComponentContext() smgr = ctx.getServiceManager() obj = smgr.createInstanceWithContext( .. , ctx) | CreateUnoService() | 
| See Opening a Dialog | CreateUnoDialog() | 
| CreateUnoListener() | |
| Див. Типи даних UNO | CreateUnoValue() CreateObject() | 
| Use "==" or "!=" comparison operators | 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 | 
Similarly to LibreOfficeDev 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 LibreOfficeDev Application Programming Interface (API) or download LibreOfficeDev Software Development Kit (SDK).
Importing a Python document embedded module is illustrated below, exception handling is not detailed:
            import uno, sys, zipimport
            
            def load_library(library_name: str, module_name=None):
                """ завантажити бібліотеку і імпортувати модуль
                
                Адаптовано з 'Bibliothèque de fonctions' від Губерта Ламберта (Hubert Lambert)
                на https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213"""
                doc = XSCRIPTCONTEXT.getDocument()  # поточний документ
                url = uno.fileUrlToSystemPath( \
                    '{}/{}'.format(doc.URL, 'Scripts/python'+library_name))  # ConvertToURL()
                if not url in sys.path:  # додати шлях, якщо потрібно
                    sys.path.insert(0, url)  # doclib отримує піоритет
                if module_name:  # імпортувати, якщо запитано
                    return zipimport.zipimporter(url).load_module(module_name)
            
            def import_embedded_python():
                ui = load_library("my_gui",'screen_io')  # додати <lib> шлях + імпортувати <module>
                ui.MsgBox(sys.modules.keys())
            
            g_exportedScripts = (import_embedded_python,)  # Public macros