如何从java类调用python方法?

时间:2012-02-21 17:10:48

标签: java python methods jython

我在Java项目中使用Jython。

我有一个Java类:myJavaClass.java和一个Python类:myPythonClass.py

public class myJavaClass{
    public String myMethod() {
        PythonInterpreter interpreter = new PythonInterpreter();
        //Code to write
    }
 }

Python文件如下:

class myPythonClass:
    def abc(self):
        print "calling abc"
        tmpb = {}
        tmpb = {'status' : 'SUCCESS'}
        return tmpb

现在问题是我想从我的Java文件的abc()方法调用我的Python文件的myMethod方法并打印结果。

4 个答案:

答案 0 :(得分:13)

如果我向右阅读the docs,您只需使用eval功能:

interpreter.execfile("/path/to/python_file.py");
PyDictionary result = interpreter.eval("myPythonClass().abc()");

或者如果你想得到一个字符串:

PyObject str = interpreter.eval("repr(myPythonClass().abc())");
System.out.println(str.toString());

如果您想从Java变量中提供一些输入,您可以事先使用set,而不是在Python代码中使用该变量名称:

interpreter.set("myvariable", Integer(21));
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)");
System.out.println(answer.toString());

答案 1 :(得分:3)

如果我们需要运行一个包含参数的python函数并返回结果,我们只需打印一下:

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class method {

public static void main(String[] args) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("/pathtoyourmodule/somme_x_y.py");
    PyObject str = interpreter.eval("repr(somme(4,5))");
    System.out.println(str.toString());

}

somme是python模块中的函数somme_x_y.py

def somme(x,y):
   return x+y

答案 2 :(得分:1)

没有任何方法可以做到(我知道)。

但你有几个选择:

1)从java中执行python,如下所示:

try {
    String line;
    Process p = Runtime.getRuntime().exec("cmd /c dir");
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    while ((line = bri.readLine()) != null) {
        System.out.println(line);
    }
    bri.close();
    while ((line = bre.readLine()) != null) {
        System.out.println(line);
    }
    bre.close();
    p.waitFor();
    System.out.println("Done.");
}
catch (Exception err) {
    err.printStackTrace();
}

2)你可以使用Jython这是“用Java编写的Python编程语言的实现”,从那里你可能会有更多运气做你想要的。

3)您可以使用套接字或共享文件以某种方式使两个应用程序进行通信

答案 3 :(得分:0)

你可以download here Jython 2.7.0 - Standalone Jar。

然后......

  1. 将此添加到eclipse中的java路径......
  2. 在Package Explorer(左侧)中,右键单击Java项目并选择Properties。
  3. 在左侧的树视图中,选择Java Build Path。
  4. 选择“库”选项卡。
  5. 选择添加外部JAR ...
  6. 浏览您的Jython安装(对我来说是C:\ jython2.5.2),然后选择jython.jar。
  7. 点击“应用并关闭。”
  8. 则...

    Java class (main) //use your won package name and python class dir
    -----------------
    package javaToPy;
    import org.python.core.PyObject;
    import org.python.util.PythonInterpreter;
    
    public class JPmain {
    
        @SuppressWarnings("resource")
        public static void main(String[] args) {
    
        PythonInterpreter interpreter = new PythonInterpreter();
    
        //set your python program/class dir here
        interpreter.execfile
        ("C:\\Users\\aman0\\Desktop\\ME\\Python\\venv\\PYsum.py");
    
        PyObject str1 = interpreter.eval("repr(sum(10,50))");
        System.out.println(str1.toString());
    
        PyObject str2 = interpreter.eval("repr(multi(10,50))");
        System.out.println(str2.toString());
    
    
        interpreter.eval("repr(say())");
    
    
        interpreter.eval("repr(saySomething('Hello brother'))");
    
    }
    
    }
    
    ---------------------------
    Python class
    ------------
    
    def sum(x,y):
        return x+y
    
    def multi(a,b):
        return a*b
    
    def say():
        print("Hello from python")
    
    def saySomething(word):
        print(word)`enter code here`
    
相关问题