【发布时间】:2017-05-24 05:42:42
【问题描述】:
我正在使用 py4j 进行 python 和 java 之间的通信。我可以从 java 端调用 python 方法。但是从 python 我无法发送任何对象或调用 java 方法。这是我尝试过的代码。
我的java 代码:
public interface IHello {
public String sayHello();
public String sayHello(int i, String s);
// public String frompython();
}
//ExampleClientApplication.java
package py4j.examples;
import py4j.GatewayServer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExampleClientApplication extends Thread {
public void run(){
System.out.println("thread is running...");
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
GatewayServer.turnLoggingOff();
GatewayServer server = new GatewayServer();
server.start();
IHello hello = (IHello) server.getPythonServerEntryPoint(new Class[] { IHello.class });
try {
System.out.println("Please enter a string");
String str = br.readLine();
System.out.println(hello.sayHello(1, str));
} catch (Exception e) {
e.printStackTrace();
}
ExampleClientApplication t1 = new ExampleClientApplication();
t1.start();
//server.shutdown();
}
}
我的python代码:
class SimpleHello(object):
def sayHello(self, int_value=None, string_value=None):
print(int_value, string_value)
return "From python to {0}".format(string_value)
class Java:
implements = ["py4j.examples.IHello"]
# Make sure that the python code is started first.
# Then execute: java -cp py4j.jar
py4j.examples.SingleThreadClientApplication
from py4j.java_gateway import JavaGateway, CallbackServerParameters
simple_hello = SimpleHello()
gateway = JavaGateway(
callback_server_parameters=CallbackServerParameters(),
python_server_entry_point=simple_hello)
【问题讨论】:
-
您能更具体地谈谈您的问题吗? “无法发送”是什么意思?到目前为止,您尝试过什么?
-
如果您能够接收到“From python to ...”,则 Python 进程可以明确地与 Java 端进行通信。您确实需要提供更多详细信息(输出、错误消息等)
-
1.你有缩进错误,我已经更正了。检查您的来源。 2. 你传递了
class SimpleHello(),但没有引用def sayHello(...。那么def sayHello(...将如何调用?