【问题标题】:py4j.protocol.Py4JNetworkError : An error occurred while trying to connect to the Java serverpy4j.protocol.Py4JNetworkError : 尝试连接到 Java 服务器时出错
【发布时间】:2023-03-29 05:56:01
【问题描述】:

我有以下来自 py4j 文档的简单示例:

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()

我尝试运行它,但收到以下错误:

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 服务器,我应该做些什么?谢谢!

【问题讨论】:

    标签: java python py4j


    【解决方案1】:

    其实我需要单独启动JavaGateway。即先运行以下 Java 应用程序,然后 python 将工作。

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2016-12-03
      • 2020-01-07
      • 2020-10-14
      • 2018-09-22
      • 1970-01-01
      • 2018-10-07
      相关资源
      最近更新 更多