2013-05-09 67 views
3

我知道jython允許我們從任何Java的類文件中調用java方法,就好像它們是爲python寫的一樣,但反過來可能嗎?我們可以從java調用python方法嗎?

我已經有很多使用python編寫的算法,它們在python和jython中工作得很好,但它們缺少一個合適的GUI。我打算把GUI帶入java並保持python庫不變。我無法用jython或python編寫好的GUI,而且我也無法用python編寫好的算法。所以我找到的解決方案是合併java的GUI和python的庫。這可能嗎。我可以從java調用python的庫嗎?

+1

不以同樣的方式沒有了,更重要的是有沒有理由。 – Serdalis 2013-05-09 11:27:30

+0

答案是否適合您的需求?如果他們解決了您的問題,請選擇一個答案,這樣問題就不會被標記爲未答覆。謝謝 – Dropout 2013-05-10 07:19:13

回答

12

是的,這可完成。通常這將通過創建一個PythonInterpreter對象,然後使用它來調用python類來完成。

請看下面的例子:

的Java:

import org.python.core.PyInstance; 
import org.python.util.PythonInterpreter; 


public class InterpreterExample 
{ 

    PythonInterpreter interpreter = null; 


    public InterpreterExample() 
    { 
     PythonInterpreter.initialize(System.getProperties(), 
            System.getProperties(), new String[0]); 

     this.interpreter = new PythonInterpreter(); 
    } 

    void execfile(final String fileName) 
    { 
     this.interpreter.execfile(fileName); 
    } 

    PyInstance createClass(final String className, final String opts) 
    { 
     return (PyInstance) this.interpreter.eval(className + "(" + opts + ")"); 
    } 

    public static void main(String gargs[]) 
    { 
     InterpreterExample ie = new InterpreterExample(); 

     ie.execfile("hello.py"); 

     PyInstance hello = ie.createClass("Hello", "None"); 

     hello.invoke("run"); 
    } 
} 

的Python:

class Hello: 
    __gui = None 

    def __init__(self, gui): 
     self.__gui = gui 

    def run(self): 
     print 'Hello world!' 
1

您可以使用Jython從Java代碼中輕鬆調用python函數。只要您的python代碼本身在jython下運行,即不使用某些不受支持的c-extensions。

如果這對你有用,它肯定是你可以得到的最簡單的解決方案。否則,您可以使用新的Java6解釋器支持中的org.python.util.PythonInterpreter。

從我的頭頂一個簡單的例子 - 但應該工作,我希望:(檢查完成沒有錯誤爲了簡潔)

PythonInterpreter interpreter = new PythonInterpreter(); 
interpreter.exec("import sys\nsys.path.append('pathToModiles if they're not there by default')\nimport yourModule"); 
// execute a function that takes a string and returns a string 
PyObject someFunc = interpreter.get("funcName"); 
PyObject result = someFunc.__call__(new PyString("Test!")); 
String realResult = (String) result.__tojava__(String.class); 

SRC Calling Python in Java?

相關問題