2015-06-26 27 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