2013-05-09 81 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?

相关问题