我正在尝试调用python函数从java(groovy)中传递HashMap。 python函数对输入映射中的每个值进行平方,并返回具有相同键的方形字典。
JythonTest.groovy
import org.python.util.PythonInterpreter
import org.python.core.*;
class JythonTest
{
static main(def args)
{
PythonInterpreter pi;
pi = new PythonInterpreter()
pi.exec("from py1 import square3")
PyFunction pf = (PyFunction)pi.get("square3")
def map = ["value1":1,"value2":2,"value3":3] //groovy map
PyDictionary pyDict = new PyDictionary(map)
pf.__call__(pyDict) //this is line 16 at which according to stack trace the exception is originated (as python function call occurs here)
}
}
py1.py
def square3(map):
squareMap = {}
for k,v in map.items(): #this is line 3 where according to stack trace exception is occurring
squareMap[k] = v*v
return squareMap
但我收到以下错误:
Exception in thread "main" Traceback (most recent call last):
File "__pyclasspath__/py1.py", line 3, in square3
java.lang.ClassCastException: java.lang.String cannot be cast to org.python.core.PyObject
at org.python.core.PyDictionary.dict_items(PyDictionary.java:659)
at org.python.core.PyDictionary$dict_items_exposer.__call__(Unknown Source)
at org.python.core.PyObject.__call__(PyObject.java:449)
at py1$py.square3$1(__pyclasspath__/py1.py:5)
at py1$py.call_function(__pyclasspath__/py1.py)
at org.python.core.PyTableCode.call(PyTableCode.java:167)
at org.python.core.PyBaseCode.call(PyBaseCode.java:138)
at org.python.core.PyFunction.__call__(PyFunction.java:413)
at org.python.core.PyFunction.__call__(PyFunction.java:408)
at org.python.core.PyFunction$__call__.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
at JythonTest.main(JythonTest.groovy:16)
java.lang.ClassCastException: java.lang.ClassCastException: java.lang.String cannot be cast to org.python.core.PyObject
在异常堆栈跟踪中,它说异常在python文件第3行。但是当我从python本身调用python函数时,比如在py1.py
的末尾附加下面的行:
a = square3({"val1":1,"val2":2})
print(a)
我得到以下输出:
{'val2': 4, 'val1': 1}
那么为什么从java调用python函数会失败?我不知道这里出了什么问题。为什么要调用pf.__call__(pyDict)
抛出此类异常?