【发布时间】:2014-03-27 19:27:22
【问题描述】:
我想使用“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')
【问题讨论】:
-
我对 jython 不是很熟悉,但是如果您尝试改用
.get("helloworld")会发生什么?或者如果你.getLocals()怎么办? -
不...不走运,抛出 TypeError: call of non-function (instance of 'org.python.core.PyStringMap') with getLocals
-
如果你在做
import helloworld而不是from helloworld import helloworld,类构造函数会不会是helloworld.helloworld()? -
另外,
def init(self): fake = ...应该是def __init__(self): self.fake = ...和getName应该采用self如果你将假存储在实例变量中。