【问题标题】:Run Python code inside LibreOffice在 LibreOffice 中运行 Python 代码
【发布时间】:2017-10-04 13:55:28
【问题描述】:

我目前正在尝试从 MATLAB 下车并用 Python 替换它。我一直喜欢 MATLAB 的一个功能是(现已弃用)笔记本。基本上,这允许人们在 Microsoft Word 文件中运行 MATLAB 代码并获得输出。这是某种 iPython / Jupyter Notebook 风格。现在我想问一下,Libre Office Writer中是否有类似的Python编程概念。 Jupyter 对我来说不是一个选择,因为我想要所见即所得的编辑以及从我的笔记本中的其他应用程序复制和粘贴图像的能力。

MATLAB Notebook

感谢您的任何提示!

彼得

PS:我不是在寻找“Libre Office 宏编程”。

【问题讨论】:

    标签: python matlab jupyter-notebook libreoffice-writer


    【解决方案1】:

    不知道有什么内置的方式,不过我们可以做一个,改编自How do I execute a string containing Python code in Python?先设置如下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,
    

    现在在 Writer 中,输入以下内容。

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

    然后选择这三行并通过转到工具 -> 宏 -> 运行宏来运行宏。

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      相关资源
      最近更新 更多