使用PythonInterpreter時發生的java.lang.ClassCastException

2024-05-16 07:46:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从java函数中调用它。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

^{pr2}$

但我得到了以下错误:

^{3}$

在异常堆栈跟踪中,它表示异常在python文件第3行中。但是当我从python本身调用python函数时,比如在py1.py末尾附加以下一行:

a = square3({"val1":1,"val2":2})
print(a) 

我得到以下输出:

{'val2': 4, 'val1': 1}

那么为什么从java调用python函数失败呢?我不想在这里出什么问题。为什么调用pf.__call__(pyDict)引发这样的异常?在


Tags: 函数orgimportmapdefpijavacall