2015-06-26 26 views
1

我已将控制台输出重定向到以下代码的txt文件,但是有没有办法将结果分配给本地变量?例如如果输出是'Hello World',我想把它分配给一个String变量。Jython中的PythonInterpreter - 存储结果

我在看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"); 

} 

回答

0

为了得到执行的Python脚本的命令行输出到Java串,首先创建一个java.io.ByteArrayOutputStreamhttps://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),它将表达式的结果作为PyObject返回。在PyObject上,您可以使用Jython-API将其转换为相应的Java标准类型或执行您想要的任何操作。如果您想使用更复杂的脚本(而不是单个表达式),则可以使用interp.get(variable name)将由脚本创建的某些对象作为PyObject s进行检索。

+0

嗨stewori,感谢您的意见。我会试试这个。 – user3742439