Can I run code in a python macro and print output to a console? I’ve tried the following code based on the links it contains.
This code does not print to the console:
# https://help.libreoffice.org/latest/bo/text/sbasic/python/python_shell.html#N0127
def interpreter_console():
import uno, os, subprocess
ctx = XSCRIPTCONTEXT.getComponentContext()
smgr = ctx.getServiceManager()
ps = smgr.createInstanceWithContext("com.sun.star.util.PathSettings", ctx)
install_path = uno.fileUrlToSystemPath(ps.Module)
pgm = install_path + os.sep + "python" # Python shell/console path
subprocess.Popen(pgm) # Start Python interactive Shell
print("Hi")
The testhelpers
macro generates an error unless apso has been launched before running (which I’m trying to avoid). It prints to the console if it is open, otherwise it just opens the console without printing.
# https://gitlab.com/jmzambon/apso#helpers
def testhelpers():
from apso_utils import console, msgbox
## simple console:
# console()
## black&white console:
# console(BACKGROUND=0x0, FOREGROUND=0xFFFFFF)
## pass parent window to get non-modal top console:
# doc = XSCRIPTCONTEXT.getDocument()
# console(parent=doc.CurrentController.ComponentWindow)
## load currents variables into console namespace:
loc = locals()
loc.update(globals())
console(loc=loc)
## introspection tools and message box:
doc = XSCRIPTCONTEXT.getDocument()
print(doc.Title)
msgbox(doc.Title)
def entryfunc(event=None):
ctx = XSCRIPTCONTEXT.getComponentContext()
ctx.ServiceManager.createInstance("apso.python.script.organizer.impl")
# now we can import apso_utils library
from apso_utils import mri
mri(ctx)
entryfunc
might be relevant.