我正在使用 py4j 从我的 python 代码中调用 Java 方法。当我在 eclipse 上启动 java 网关并使用 python 代码调用 java 方法时,我得到了正确的响应。但是,当我在 tomcat 上部署与 war 文件相同的 java 程序,然后使用 python 代码调用部署在 tomcat 上的 java 方法时,出现以下错误。
Java代码:
package testjav;
import py4j.GatewayServer;
public class Helloworld {
public String sayhello() {
System.out.println("Hi there");
return "hi";
}
public static void main(String[] args) {
GatewayServer gatewayServer = new GatewayServer(new Helloworld());
gatewayServer.start();
System.out.println("Gateway Server Started");
}
}
蟒蛇代码:
from py4j.java_gateway import JavaGateway, GatewayParameters
gateway = JavaGateway(gateway_parameters=GatewayParameters(port=8080))
out = gateway.entry_point.sayhello()
print(out)
Tomcat 上的错误:
Python 上的错误:
Traceback (most recent call last):
File "C:\Users\******\Documents\*****\helloworld\tasksHello\tasks.py", line 24, in <module>
out = gateway.entry_point.sayhello()
File "C:\Users\******\AppData\Local\Continuum\anaconda3\lib\site-packages\py4j\java_gateway.py", line 1160, in __call__
answer, self.gateway_client, self.target_id, self.name)
File "C:\Users\*******\AppData\Local\Continuum\anaconda3\lib\site-packages\py4j\protocol.py", line 318, in get_return_value
value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
KeyError: 'T'
我通过查看 py4j 模块代码检查了这个答案变量。在 jvm run 的情况下,它返回: yshi ,因为 hi 是输出,ys 被 py4j 使用。但如果是 tomcat 答案 = 'HTTP/1.1'。我不明白为什么会这样。请指导我。