如果py4j JVM正在运行,在python中测试的最佳方法是什么?

dre*_*cko 2 python java py4j

如果运行py4j的JVM正在侦听所选的(可能是默认的)套接字,那么测试(在python脚本中)的好方法是什么?有点聪明ping吗?

我可以尝试从我的Java类访问方法或对象并捕获生成的socket.error异常,但这似乎有点像黑客.

创建一个JavaGateway没有任何JVM可以与之通信的python 实例不会引发异常.我可能错过了一些东西,但我没有在文档中找到任何内容.

Bar*_*emy 5

Py4J没有运行状况检查,ping或版本命令,所以测试Py4J是否正在监听的唯一三个选项是:

  1. 尝试连接到套接字.此方法并不完美,因为另一个服务器程序可能正在侦听默认端口.

  2. 尝试热切地加载JavaGateway(将在0.8版本中提供.现在只能在github上的master分支中使用):

    from py4j.java_gateway import JavaGateway, Py4JNetworkError
    try:
        java_gateway = JavaGateway(eager_load=True)    
        print("JVM accepting connection")
    except Py4JNetworkError:
        print("No JVM listening")
    except Exception:
        print("Another type of problem... maybe with the JVM")
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在Py4J 0.7中,尝试调用基本的System方法:

    from py4j.java_gateway import JavaGateway, Py4JNetworkError
    
    java_gateway = JavaGateway()    
    try:
        java_gateway.jvm.System.getProperty("java.runtime.name")
        print("JVM accepting connection")
    except Py4JNetworkError:
        print("No JVM listening")
    except Exception:
        print("Another type of problem... maybe with the JVM")
    
    Run Code Online (Sandbox Code Playgroud)

欢迎功能请求!