Designing & Developing Python Applications
- 1 Introduction
- 2 Documentation
- 3 Unified Modeling Language (UML)
- 4 Preamble
- 5 Developing
- 6 Debugging
- 6.1 Within LibreOffice
- 6.2 From an IDE via LibreOffice Python interpreter
- 6.3 Console on Windows
- 6.4 Handling Exceptions - draft
- 7 Building Dialogs - draft
- 8 Dispatcher commands - draft
- 9 Writing extensions - draft
This page is intended for Python macros developers wishing to design or collaborate to LibreOffice applications. Beginners to experienced Python coders may benefit from this page's development guidelines. A discovery of Python within LibreOffice is available from Python Programmer's Guide.
This page assumes you have a reasonable exposure to Python as well as you have some familiarity with LibreOffice application suite. It contains some Python code samples as well as LibreOffice extensions usage that are briefly described.
- Python.org of course
- Learn Python the hard way not as hard as it says
- Python - Apache OpenOffice
- The Hitchhiker's Guide to Python!, Kenneth Reitz, April 2018
- Object-Oriented Programming in Python, Nov. 2017 as PDF
- OpenOffice.org 3.1 Developer's Guide, online version, and examples, 2009
- StarOffice (Basic) Programmer's Tutorial, May 2000
- Java LibreOffice Programming, Andrew Davison, March 2017
Unified Modeling Language (UML)
Numerous UML-driven tools are available. Herewith is an arbitrary list that focuses on free open source interoperable applications mentioning their featured languages.
- ArgoUML : ArgoUML is running on any Java platforms and is available in ten languages (American English, British English, French, German, Italian, Portuguese, Spanish, Russian, Norwegian Bokmål and Chinese).
- StarUML : StarUML is proposed for macOS 10.6+, Windows XP+ and Ubuntu (64 or 32-bit). StarUML has a rich feature list and is available in English only.
- Umbrello : Multi-lingual Umbrello comes with GNU/Linux distributions, Windows (64 or 32-bit) and macOS.
Basic language macros development in LibreOffice comes with an Integrated Development Environment (IDE) that allows Basic macros to be edited, debugged and the like. Writing Python macros requires extra configuration steps in order to build your IDE of choice. In return you are provided with flexible design experience built upon your Python developing preferences or habits. Hereafter are IDE setup guidelines that range from beginner to advanced user.
The handling of libraries and macros equivalent to that of Basic is not available for Python. However managing Python traditional modules and functions is quite possible, while the building of Python packages translates somehow partially to creating LibreOffice extensions or UNO packages. This page uses interchangeably modules for libraries and functions for macros. Python's terminology may be preferred in order to better accommodate Python's cultural usage.
LibreOffice scripts come in three distincts flavors, they can be personal, shared or embedded in documents. Depending on their types and depending on the platform, they end up being stored in varying locations that are detailed here.
To manage Python scripts one can either use Windows libraries either resort to GNU/Linux file manager shortcuts. Thus .py files can be organised using casual drag & drop. A description of folder locations according to your environment to help you setting up libraries or file manager shortcuts can be found there.
Python projects can be arranged per IDE in a subsequent Windows library as illustrated.
The must-have Alternative Python Script Organizer extension leverages Python scripts management. You get greater Python scripts integration in LibreOffice by installing it. Once LibreOffice is restarted, check Tools menu for Macros - Organize python scripts sub-menu.
This extension proposes various actions in order to manage Python scripts. The Execute button runs the selected macro. Actions available from Menu button depend on the selected element:
- Create macro or library whenever you select personal, shared or document containers
- Edit, Rename, Delete a macro or library
- Embed a macro into a document from personal or shared containers
- Substitute a document embedded library with a platform Python module
- Export a document embedded library as a Python module
- Debug the selected macro
- Run Python interactive console also as known as Python interpreter
Other information related to scripts organization and Python packages can be found in Debugging
Script LibreOffice details how to use scripts in LibreOffice application suite.
Numerous softwares make use of Python, either natively, either specifically. LibreOffice embeds its own Python interpreter which permits to use the API through Universal Network Objects (UNO). Python language holds its own interpreter that can be used in parallel to that of LibreOffice. Both share a common base and are extensible, thus they provide identical features as well as they offer different ones. Native Python does not include the UNO interface to LibreOffice API. Reversely LibreOffice does not fully behave as native Python and does not extend its functionalities the exact same way as native Python. However neither LibreOffice nor native Python facilitate application development with Python language for Writer, Calc, Impress, Draw, Base or Math.
LibreOffice exists in 32bits or 64bits versions. The Integrated Development Environment (IDE) that accompany it requires to execute in the same context, both in 32bits or both in 64bits. Numerous IDEs exist from the easiest like IDLE, although disputable, to more elaborated ones like PyCharm or PyDev for Eclipse. The following list arbitrarily focuses on tools that are free, open source, multi platform and possibly multi lingual. Below Debugging chapter uses Pyzo and PyCharm solely for illustration. A list of IDEs for Python is available from Python.org site. A comparison of Integrated Development Environments (IDE) for numerous languages is available from Wikipedia.
- Integrated Development and Learning Environment (IDLE) supports 32bits and 64bits. It is available on many platforms. IDLE is the recommended tool to learn Python.
- Geany operates in 32bits or 64bits and talks 43 different languages. It runs on GNU/Linux, *BSD, macOS, AIX v5.3, Solaris Express and Windows. Geany is light, fits small projects and supports LibreOffice Python interpreter.
- Debugging with Aptana looks possible cf. this thread
- PyCharm (free edition) supports Gnu/Linux, macOS and Windows platforms. It is available as 32bits, and apparently accommodates 64bits too. Along with numerous features accompanying Python development, PyCharm holds a Python debugger that's compatible with LibreOffice.
- Pyzo is available for Linux, OS X and Windows in 10 different languages. Multiple Python interpreters can be configured, be they 32bits or 64bits. Pyzo offers debugging facilities.
Here's a list of features available from these IDEs, LibreOffice Basic IDE does not offer some of them.
Source Explorer, Syntax Highlighting
Source exploration and syntax highlighting within IDLE, Geany and PyCharm are facilitating script edition. Geany and PyCharm support code folding. IDLE class browser does not support inner or embedded classes.
Code completion assists the edition of Python scripts in IDLE, Geany and PyCharm.
Debugging chapter below goes into this subject in more details.
Coding guidelines (PEP) - draft
Test-Driven Development (TDD) - draft
A source code local history comes with PyCharm as illustrated below:
Two copies of apso.py Python module are jointly displayed and respectively labelled v0.8.3 and v0.8.7. Version differences are precisely highlighted.
PyCharm supports other version control solutions (VCS) such as Git, GitHub, Mercurial, Perforce or Subversion.
One can edit and debug Python macros directly within LibreOffice with the help of Alternative Python Script Organizer extension. Managing libraries and modules is possible, as well as selecting your preferred editor without leaving LibreOffice.
Developing out of LibreOffice is equally feasible, thus debugging becomes possible. Remote coding and testing using an Integrated Development Environment (IDE) brings more features detailed hereafter.
It is not always clear at design time which services a UNO object actually supports. However extensions that help the developer to inspect arbitrary UNO-Objects exist, but are not made available from the extensions' catalog, with the exception of MRI. They're built upon LibreOffice API reflection ability.
- X-Ray inspects LibreOffice API objects. It displays the properties, methods, services, interfaces which are provided by an object variable. X-Ray is available in french, english, german, spanish, czech, polish and russian. X-Ray is written in Basic.
- MRI (My Reflection and Introspection) is an introspection tool of UNO objects, written in Python. Its features are similar to that of X-Ray. MRI is available in english only. Note: Extensions' catalog MRI copy is outdated.
- Object Inspector The Object Inspector extension displays the total capabilities of an UNO-object such as all supported services, exported interfaces, and their respective methods and properties in a TreeView window. The Object Inspector is written in Java and is available only in english.
Usage of Python macros
Python macros in LibreOffice are stored in numerous locations and come in varied species as explained in Python as a macro language. Scripts can be personal, shared, stored in extensions, integrated in packages or embedded in documents. This diversity imply different uses or constraints.
- In a document each module is autonomous, no module import.
- Calling a Basic or Python extension from an embedded Python module is possible.
- Python scripts in <user>\python\pythonpath can be imported by embedded modules or by <user>\python scripts.
- No Basic support from an IDE: No X-Ray.
- Python and Java are supported when invoked from an IDE: MRI, Object Inspector can be used.
Here's how to use Mri in a Python macro:
import uno def mri(target): ctx = uno.getComponentContext() mri = ctx.ServiceManager.createInstanceWithContext( "mytools.Mri",ctx) mri.inspect(target) if __name__ == '__main__': def Mri_test(): document = XSCRIPTCONTEXT.getDocument() mri(document) Mri_test()
Stopping a running macro with X-Ray :
import uno from com.sun.star.uno import RuntimeException as _rtex def xray(myObject): try: sm = uno.getComponentContext().ServiceManager mspf = sm.createInstanceWithContext("com.sun.star.script.provider.MasterScriptProviderFactory", uno.getComponentContext()) scriptPro = mspf.createScriptProvider("") xScript = scriptPro.getScript("vnd.sun.star.script:XrayTool._Main.Xray?language=Basic&location=application") xScript.invoke((myObject,), (), ()) return except: raise _rtex("\nBasic library Xray is not installed", uno.getComponentContext()) # ___________ example of use _______________ def demoXray(): """ example : using xray in a Writer document """ xTextDoc = XSCRIPTCONTEXT.getDocument() xText = xTextDoc.Text xray(xText) xray("Demo is finished") g_exportedScripts = demoXray,
Displaying UNO objets in a tree view using Object Inspector :
import uno def inspectObject( obj, title="Object Inspector" ): ctx = uno.getComponentContext() oi = ctx.ServiceManager.createInstanceWithContext("org.openoffice.InstanceInspector", ctx) if oi is None: # i.e. InstanceInspector is not installed or deactivated return # exit silently oi.inspect( obj, title ) def exObjInspector(): doc = XSCRIPTCONTEXT.getDocument() dsk = XSCRIPTCONTEXT.getDesktop() inspectObject(doc) inspectObject(dsk, title="StarDesktop")
From an IDE via LibreOffice Python interpreter
Developing Python macros within an IDE requires the use of LibreOffice interpreter. Native Python comes with IDLE's interpreter that's not compatible with UNO objects. While selecting a Python IDE programmers benefit from numerous features such as class browser, syntax highlighting, code completion, coding standards enforcement, test driven development, debugging, version control and many more.
The setting of LibreOffice Python interpreter for Geany, PyCharm or Pyzo is illustrated in Python IDE Basics.
In order to execute a script from <user>\python or from <user>\python\pythonpath, a communication must be established between the IDE and LibreOffice. UNO objects are not reachable without such a bridge. Once a communication is in place, the EDI and LibreOffice operate together. The following links document that process:
- A bridge for IDE with XSCRIPTCONTEXT revisité, Feb. 2017 (in french)
- Interface-oriented programming in OpenOffice / LibreOffice : automate your office tasks with Python Macros, Dec. 2015
- Macro creation of LibreOffice with PyCharm (environment setting) Sep. 2013 (from japanese)
- Starting, Stopping, and Connecting to OpenOffice with Python, Dec. 2008
- Python UNO-bridge, Oct. 2008
Usage of Python scripts
- ...calling Python packages...
External Execution with Geany
Geany initiates the opening of a window within LibreOffice. Geany EDI invokes info() function, which utilizes ..awt.createMessageBox API method defined in the SDK. The user script is named SysInfo.py.
Debugging with PyZo
PyUNO Workspace is a object introspection Pyzo IDE plugin for PyUNO and LibreOffice UNO API:
Debugging with PyCharm
PyCharm's debugger displays UNO objects, Python classes or objects:
Console on Windows
By default, there is no default stdout on Windows. What is sent by function “print” will not be visible anywhere. To get a console to be used as stdout, apply the following instructions.
- Close LibreOffice.
- Download Visual Studio Express 2010 C++ (I assume it may work with other versions) and install it.
- Open the Console for Visual Studio.
editbin.exe /subsystem:console "C:\Program Files\LibreOffice 5\program\soffice.exe" editbin.exe /subsystem:console "C:\Program Files\LibreOffice 5\program\soffice.bin"
cf. EditBin reference at TechNet
Now, a console will be shown when you open LibreOffice. It will be the stdout for the “print” command. And you can get Python errors while LO is running if you use traceback.
import traceback […] try: […] except: traceback.print_exc()
But syntax errors still won’t be reported there.
Handling Exceptions - draft
Building Dialogs - draft
- UNODiT UNO Dialog Tools
- Using Dialogs in Components
- Events help pages
- Events API pages
- more: Updating ToC with automated script, [Calc] Event-Listeners & Handlers, Auto execute .. macro by code, .. python script to monitor OnSave event, Looking for an example in Python for a 2-button dialog, Python...MouseClick in ListBox, Dialog box in Python, [Python][UI] Refresh window/widget, Run a python macro when cell contents change, HowTo .. Python macro for Calc
Dispatcher commands - draft
Interface-oriented programming in *Office, Christopher Bourez (2015)