我已经将控制台输出重定向到下面代码的txt文件中,但是是否有方法将结果分配给局部变量呢?例如,如果输出是'Hello‘,我想将它赋值给一个字符串变量。
我在看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");
}发布于 2015-06-30 15:14:13
要将执行的Python-脚本的命令行输出转换为Java,首先创建一个java.io.ByteArrayOutputStream (https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html);让我们将其称为bout。然后打电话给interp.setOut(bout)。调用interp.execfile(...)之后,您应该能够通过bout.toString()以Java的形式检索其输出。
但是,通常情况下,不通过系统输出/输入来完成这样的事情会更优雅。相反,您可以使用interp.eval(some python expression),它将表达式的结果作为PyObject返回。在PyObject上,您可以使用Jython将其转换为相应的Java标准类型,或者任意使用它。如果您想使用更复杂的脚本(而不是单个表达式),可以使用interp.get(variable name)检索脚本创建的某些对象为PyObject。
https://stackoverflow.com/questions/31075385
复制相似问题