1

I'm currently trying to get off from MATLAB and replace it by Python. A functionality I loved always in MATLAB are the (now deprecated) notebooks. Basically, this allows one to run MATLAB code inside a Microsoft Word file and get the output. It's some kind of the iPython / Jupyter Notebook style. Now I would like to ask, wherther there is a similar concept for Python programming in Libre Office Writer. Jupyter is not an option for me, since I want stuff like WYSIWYG editing and the capability of copy-and-paste images from other applications in my Notebook.

MATLAB Notebook

Thank you for any hints!

Peter

PS: I'm not looking for "Libre Office Macro programming".

P. Egli
  • 167
  • 1
  • 4

1 Answers1

0

I do not know of any built-in way, but we can make one, adapted from How do I execute a string containing Python code in Python? First set up the following Python macro.

import uno
import sys
import io

def run_selected_code():
    oDoc = XSCRIPTCONTEXT.getDocument()
    xTextCursor = oDoc.CurrentController.Selection.getByIndex(0)
    xText = xTextCursor.getText()
    codeOut = io.StringIO()
    codeErr = io.StringIO()
    sys.stdout = codeOut
    sys.stderr = codeErr
    exec(xText.getString())
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    err_string = codeErr.getvalue()
    text = oDoc.getText()
    cursor = text.createTextCursor()
    cursor.gotoEnd(False)
    #text.insertString(cursor, "\n\nerror:\n%s\n" % err_string, False)
    out_string = codeOut.getvalue()
    text.insertString(cursor, "\n\noutput:\n%s" % out_string, False)
    codeOut.close()
    codeErr.close()

g_exportedScripts = run_selected_code,

Now in Writer, enter the following.

a = 5
b = 7
print("%d + %d = %d" % (a, b, a + b))

Then select these three lines and run the macro by going to Tools -> Macros -> Run Macro.

Writer result

Jim K
  • 12,824
  • 2
  • 22
  • 51