从Java调用Python模块

10 投票
1 回答
12593 浏览
提问于 2025-04-18 00:12

我想通过“PythonInterpreter”在Java中调用一个Python模块里的函数,下面是我的Java代码:

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");

PyObject someFunc = interpreter.get("helloworld.getName");

PyObject result = someFunc.__call__();

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

而Python代码(helloworld.py)如下:

    from faker import Factory
    fake = Factory.create()

    def getName():
       name = fake.name()
       return name  

我遇到的问题是,当我调用interpreter.get时,它返回了一个空的PyObject。

有没有人知道这是怎么回事?我的Python代码在IDLE中运行得很好。

编辑

我刚刚对代码做了一些修改,如下:

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");


PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");  

PyObject result = wrapper.invoke("getName()");

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

我在我的Python模块中引入了一个类:

from faker import Factory

class helloworld:

def init(self):
    fake = Factory.create()

def getName():
    name = fake.name()
    return name 

现在我得到了下面的错误:

Exception in thread "main" Traceback (innermost last):
  File "<string>", line 1, in ?
TypeError: call of non-function (java package 'helloworld')

1 个回答

5
  1. 你不能在 PythonInterpreter.get 里用点(.)来访问Python的属性。你只需要用属性的名字来获取模块,然后从这个模块中取出属性。
  2. (编辑部分) Python代码完全是错的。请看下面的正确示例。当然,还有 www.python.org
  3. (编辑部分) PyInstance.invoke 的第一个参数应该是方法的名字。
  4. 下面你可以找到两个案例的有效代码示例。

Main.java

import org.python.core.*;
import org.python.util.PythonInterpreter;

public class Main {

    public static void main(String[] args) {
        test1();
        test2();
    }

    private static void test1() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import hello_world1");
        PyObject func = interpreter.get("hello_world1").__getattr__("get_name");
        System.out.println(func.__call__().__tojava__(String.class));
    }

    private static void test2() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("from hello_world2 import HelloWorld");
        PyInstance obj = (PyInstance)interpreter.eval("HelloWorld()");
        System.out.println(obj.invoke("get_name").__tojava__(String.class));
    }
}

hello_world1.py

def get_name():
    return "world"

hello_world2.py

class HelloWorld:
    def __init__(self):
        self.world = "world"

    def get_name(self):
        return self.world

撰写回答