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

标签 java python

<分区>

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

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

最佳答案

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

关于java - 我们可以从 java 调用 python 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16460468/

相关文章:

java - 根据文本字段中的文本从数据库填充 jcombobox

python - 将 url 编码为唯一的短文件名

python - Airflow Dag 不会因 python 脚本失败而失败

python - 程序未返回正确答案(计算最小周长)

python - 使用Python3显示年龄(以秒为单位)

python - 通过 PyQt4 在 QT 中绘制图形 ALA Graphviz

java - 加工中的打地鼠

java - 使用 .NET 中的 java 库

java - 通过java发送邮件: multiple sender with different mail id

java - 如何将 JLabel 转换为字符串,反之亦然?