Jython 中的 PythonInterpreter - 存储结果

PythonInterpreter in Jython - storing result

我已经将控制台输出重定向到下面代码的 txt 文件,但是有没有办法将结果分配给局部变量呢?例如如果输出是 'Hello World' 我想将其分配给一个字符串变量。

我正在看 PythonInterpreter API,我有点困惑,因为它对我来说是新的 (http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html).

我一直在研究 setIn 和 setOut 方法,但没有成功。

非常感谢您的建议。

public static void main(String[] args) {

    // Create an instance of the PythonInterpreter
    PythonInterpreter interp = new PythonInterpreter();

    // The exec() method executes strings of code
    interp.exec("import sys");
    interp.exec("print sys");

    interp.execfile("C:/Users/A/workspace/LeaerningPyDev/helloWorld.py");

}

要将执行的 Python-脚本的命令行输出转换为 Java-String,首先创建一个 java.io.ByteArrayOutputStream (https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html);我们称它为 bout。然后打电话 interp.setOut(bout)。调用 interp.execfile(...) 后,您应该能够通过 bout.toString().

将其输出检索为 Java-String

然而,一般来说,不通过 system-out/in 做这样的事情更为优雅。相反,您可以使用 interp.eval(some python expression),其中 returns 表达式的结果作为 PyObject。在 PyObject 上,您可以使用 Jython-API 将其转换为相应的 Java 标准类型,或者用它做任何您想做的事情。如果您想使用更复杂的脚本(而不是单个表达式),您可以使用 interp.get(variable name) 将脚本创建的某些对象检索为 PyObjects.