我们可以从java调用python方法吗? [英] Can we call a python method from java?

查看:96
本文介绍了我们可以从java调用python方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know jython allows us to call a java method from any java's classfile as if they were written for python, but is the reverse possible ???

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

I already have so many algorithms that written in python, they work pretty well with python and jython but they lack a proper GUI. I am planing to bring the GUI with the java and to keep the python library intact. I am not able to write a good GUI with jython or python and I cannot write a good algorithm with python. So the solution I found was to merge java's GUI and python's library. Is this possible. Can I call python's library from java.

推荐答案

是的,可以做到。通常这将通过创建 PythonInterpreter 对象然后使用它来调用python类来完成。

Yes, that can be done . Normally this will be done by creating a PythonInterpreter object and then calling the python class using that .

考虑以下内容例如:

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!'

这篇关于我们可以从java调用python方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆