我们可以从java调用python方法吗?

2024-04-25 00:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道jython允许我们从任何java的类文件中调用java方法,就好像它们是为python编写的一样,但是反过来可能吗???

我已经有很多用python编写的算法了,它们在python和jython中工作得很好,但是它们缺少一个合适的GUI。我计划将GUI与java结合起来,并保持python库的完整性。我不能用jython或python编写一个好的GUI,也不能用python编写一个好的算法。所以我找到的解决方案是合并java的GUI和python的库。这可能吗。我可以从java调用python的库吗。


Tags: 文件方法算法guijythonjava解决方案计划
2条回答

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

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);

srcCalling Python in Java?

是的,那是可以做到的。通常,这将通过创建一个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!'

相关问题 更多 >