我不知道任何内置方式,但我们可以制作一个,改编自如何在 Python 中执行包含 Python 代码的字符串? 首先设置以下Python 宏。
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))
然后选择这三行并通过转到工具 -> 宏 -> 运行宏来运行宏。
