py4j.protocol.Py4JNetworkError:尝试连接到Java服务器时发生错误 [英] py4j.protocol.Py4JNetworkError : An error occurred while trying to connect to the Java server
本文介绍了py4j.protocol.Py4JNetworkError:尝试连接到Java服务器时发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下来自py4j文档的简单示例:
I have the following simple example from the py4j document:
from py4j.java_gateway import JavaGateway
def main():
print("Hello")
gateway = JavaGateway() # connect to the JVM
random = gateway.jvm.java.util.Random() # create a java.util.Random instance
number1 = random.nextInt(10) # call the Random.nextInt method
number2 = random.nextInt(10)
print(number1,number2)
if __name__ == '__main__':
main()
我尝试运行它,但出现以下错误:
I tried to run it, but get the following error:
Traceback (most recent call last):
File "/Users/edamameQ/github/myTest/main.py", line 16, in <module>
main()
File "/Users/edamameQ/github/myTest/main.py", line 7, in main
random = gateway.jvm.java.util.Random() # create a java.util.Random instance
File "/Library/Python/2.7/site-packages/py4j/java_gateway.py", line 1188, in __getattr__
"\n" + proto.END_COMMAND_PART)
File "/Library/Python/2.7/site-packages/py4j/java_gateway.py", line 624, in send_command
connection = self._get_connection()
File "/Library/Python/2.7/site-packages/py4j/java_gateway.py", line 579, in _get_connection
connection = self._create_connection()
File "/Library/Python/2.7/site-packages/py4j/java_gateway.py", line 585, in _create_connection
connection.start()
File "/Library/Python/2.7/site-packages/py4j/java_gateway.py", line 697, in start
raise Py4JNetworkError(msg, e)
py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server
要连接到Java服务器,我应该做些什么吗?谢谢!
Is there anything I should do in order to connect to a Java server? Thanks!
推荐答案
实际上,我需要分别启动JavaGateway.即首先运行以下Java应用程序,然后运行python.
Actually I need to start the JavaGateway separately. i.e. run the following Java application first, then the python would work.
import py4j.GatewayServer;
public class myTest {
public static void main(String[] args) {
myTest app = new myTest();
// app is now the gateway.entry_point
GatewayServer server = new GatewayServer(app);
server.start();
}
}
这篇关于py4j.protocol.Py4JNetworkError:尝试连接到Java服务器时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文