简体   繁体   English

如何从java类调用python方法?

[英]How to call a python method from a java class?

I am using Jython within a Java project. 我在Java项目中使用Jython。

I have one Java class: myJavaClass.java and one Python class: myPythonClass.py 我有一个Java类: myJavaClass.java和一个Python类: myPythonClass.py

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

The Python file is as follows: Python文件如下:

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

Now the problem is I want to call the abc() method of my Python file from the myMethod method of my Java file and print the result. 现在问题是我想从我的Java文件的myMethod方法调用我的Python文件的abc()方法并打印结果。

If I read the docs right, you can just use the eval function: 如果我正确阅读文档 ,您可以使用eval函数:

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

Or if you want to get a string: 或者如果你想得到一个字符串:

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

If you want to supply it with some input from Java variables, you can use set beforehand and than use that variable name within your Python code: 如果要从Java变量中提供一些输入,可以预先使用set而不是在Python代码中使用该变量名:

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

If we need to run a python function that has parameters, and return results, we just need to print this: 如果我们需要运行一个包含参数的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 is the function in python module somme_x_y.py somme是python模块somme_x_y.py中的函数

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

There isn't any way to do exactly that (that I'm aware of). 没有任何方法可以做到这一点(我知道)。

You do however have a few options: 但是你有几个选择:

1) Execute the python from within java like this: 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) You can maybe use Jython which is "an implementation of the Python programming language written in Java", from there you might have more luck doing what you want. 2)你可以使用Jython ,它是“用Java编写的Python编程语言的一种实现”,从那里你可能会有更多运气做你想要的。

3) You can make the two applications communicate somehow, with a socket or shared file 3)您可以使用套接字或共享文件以两种方式进行通信

You can download here Jython 2.7.0 - Standalone Jar. 你可以在这里下载 Jython 2.7.0 - Standalone Jar。

Then ... 然后 ...

  1. add this to your java path in eclipse...... 将此添加到eclipse中的java路径......
  2. In the Package Explorer (on the left), right click on your Java project and select Properties. 在Package Explorer(左侧)中,右键单击Java项目并选择Properties。
  3. In the treeview on the left, select Java Build Path. 在左侧的树视图中,选择Java Build Path。
  4. Select the Libraries tab. 选择“库”选项卡。
  5. Select Add External JARs... 选择添加外部JAR ...
  6. Browse to your Jython installation (C:\\jython2.5.2 for me), and select jython.jar. 浏览到你的Jython安装(对我来说是C:\\ jython2.5.2),然后选择jython.jar。
  7. Click apply and close. 单击“应用”并关闭。

Then... 然后...

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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM