2016-02-27 289 views
3

我從py4j文件下面這個簡單的例子:py4j.protocol.Py4JNetworkError:試圖連接到Java服務器出現錯誤

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服務器呢?謝謝!

回答

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(); 
    } 
} 
相關問題