从Java调用python模块
我想使用“PythonInterpreter”从Java的python模块调用一个函数,下面是我的Java代码从Java调用python模块,java,python,Java,Python,我想使用“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
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
我面临的问题是,当我调用解释器时,它返回一个空PyObject
知道怎么回事吗?python代码在空闲状态下运行良好
编辑
我只是对代码做了一些修改,如下所示
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')
线程“main”回溯中的异常(最里面的最后一个):
文件“”,第1行,是否在中?
TypeError:调用非函数(java包“helloworld”)
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));
}
}
你好(world1.py)
def get_name():
return "world"
你好(world2.py)
class HelloWorld:
def __init__(self):
self.world = "world"
def get_name(self):
return self.world
我对jython不是很熟悉,但是如果您尝试
.get(“helloworld”)
取而代之,会发生什么呢?或者如果你.getLocals()
?不…运气不好,抛出类型错误:用getLocals调用非函数(“org.python.core.PyStringMap”)类构造函数不是helloworld.helloworld(),def init(self):fake=…
应该是def\uuuu init\uuuuu(self):self.fake=…
和getName
如果要在实例变量上存储fake,则应该采用self
。