简体   繁体   English

py4j:如何从Python启动Java Gateway

[英]py4j: how to launch the java Gateway from Python

I am able to interact with my sample Java program in Python, by opening my Java program and then using the following Python code: 通过打开Java程序,然后使用以下Python代码,我可以在Python中与示例Java程序进行交互:

from py4j.java_gateway import JavaGateway
gg = JavaGateway()
sw = gg.entry_point.getInstance()
sw.run()
...

However this has the disadvantage that I have to somehow open the Java program before using this code. 但是,这样做的缺点是,在使用此代码之前,我必须以某种方式打开Java程序。

I found that there is a method called launch_gateway which seems very convenient soo to this aim. 我发现有一个名为launch_gateway的方法对于实现此目标似乎非常方便。

py4j.java_gateway.launch_gateway(jarpath="path_to_my_jar.jar")

However, I am unable to connect to my Java program if launched in this way. 但是,如果以这种方式启动,则无法连接到Java程序。

I tried to use the following code: 我尝试使用以下代码:

port = py4j.java_gateway.launch_gateway(jarpath="path_to_my_jar.jar")
gp = GatewayParameters(port=port) 
gg = JavaGateway(gateway_parameters=gp)
sw = gg.entry_point.getInstance()

But I get the following error: 但是我收到以下错误:

An error occurred while calling t.getInstance. Trace:
py4j.Py4JException: Target Object ID does not exist for this gateway :t

I guess I am doing something wrong in the way I try to connect to the gateway. 我想我尝试连接到网关的方式出了问题。

Any suggestion? 有什么建议吗?

Thanks 谢谢

Barthelemy, you are right! 巴泰勒米,你是对的! I initially misinterpreted how this works. 我最初误解了它是如何工作的。

launch_gateway runs the gateway in py4j.jar, which is useful to interact with a standard JVM, but obviously does not contain custom code. launch_gatewaylaunch_gateway运行网关,该网关对于与标准JVM交互很有用,但显然不包含自定义代码。

However, as you suggested, the classpath parameter allows you to load additional custom Java code. 但是,按照您的建议, classpath参数允许您加载其他自定义Java代码。

This is a "minimal example": 这是一个“最小示例”:

from py4j.java_gateway import JavaGateway 
gg = JavaGateway.launch_gateway(classpath="/path/my_jar.jar")

myclass_instance = gg.jvm.my_class_package_name.MyClass()
result = myclass_instance.my_method()

Note that my_jar.jar does not have to start a gateway. 请注意, my_jar.jar不必启动网关。

launch_gateway gives you nice features such as: die_on_exit , stdout/stdin redirection, and automatic port selection. launch_gateway为您提供了不错的功能,例如: die_on_exit ,stdout / stdin重定向和自动端口选择。

I see two potential problems: 我看到两个潜在的问题:

  1. jarpath is supposed to be the path to Py4J's jar. jarpath应该是通往Py4J jar的路径。 You can add your libraries in the classpath argument of launch_gateway. 您可以将库添加到launch_gateway的classpath参数中。
  2. When you start a py4j.GatewayServer from launch_gateway, there is no entry point specified so indeed, entry_point do 当您从launch_gateway启动py4j.GatewayServer时,没有指定入口点,实际上,entry_point做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM