如何从java类调用python方法?

发布于 2025-01-07 08:33:56 字数 592 浏览 3 评论 0原文

我在 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

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

I am using Jython within a Java project.

I have one Java class: myJavaClass.java and one Python class: myPythonClass.py

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

The Python file is as follows:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

故人如初 2025-01-14 08:33:56

如果我正确阅读了 文档,您只需使用 < a href="http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#eval(org.python.core.PyObject)" rel="noreferrer">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< /code> 事先,然后在 Python 代码中使用该变量名称:

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

If I read the docs right, you can just use the eval function:

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:

interpreter.set("myvariable", Integer(21));
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)");
System.out.println(answer.toString());
女皇必胜 2025-01-14 08:33:56

如果我们需要运行一个带有参数的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

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

If we need to run a python function that has parameters, and return results, we just need to print this:

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

def somme(x,y):
   return x+y
夜夜流光相皎洁 2025-01-14 08:33:56

没有任何方法可以完全做到这一点(据我所知)。

不过,您有几个选择:

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)您可以使两个应用程序通过套接字或共享文件以某种方式进行通信

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:

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.

3) You can make the two applications communicate somehow, with a socket or shared file

残花月 2025-01-14 08:33:56

您可以此处下载 Jython 2.7.0 - 独立 Jar。

然后...

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

然后...

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`

You can download here Jython 2.7.0 - Standalone Jar.

Then ...

  1. add this to your java path in eclipse......
  2. In the Package Explorer (on the left), right click on your Java project and select Properties.
  3. In the treeview on the left, select Java Build Path.
  4. Select the Libraries tab.
  5. Select Add External JARs...
  6. Browse to your Jython installation (C:\jython2.5.2 for me), and select 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`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文