I would like to have my Python program have a loop where it sends an argument to a Java program, the Java program returns some value, and if the Python program sees that the value is what it is looking for, the loop stops. The specific Java program is linked here. My python program looks online for Minecraft server IPs and I want the Java program to return data on them. Is this possible?
Asked
Active
Viewed 160 times
2 Answers
2
Yes, it should be easily doable using a library such as Py4J, which can connect to your Java class from Python. All you have to do is to import the library, connect to the JVM like this:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
and you can call methods in the Java class like you were calling methods in Python. In your case, you would call the constructor first, like this:
java_object = gateway.jvm.mypackage.ServerPinger()
Then run whatever function you want. I'll take the ping()
method as an example:
return_object = java_object.ping("address")
The documentation in the above link is extensive and can show you how to do anything you want. Also refer to this answer written by the author of the library.

M B
- 2,700
- 2
- 15
- 20
-
There is an error. py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server (127.0.0.1:25333) – Dre Jun 26 '22 at 15:04
-
You need to run a gateway server from Java so that Python can connect to it. This is essentially similar to what the other answer suggests. Take a look at how this can be done here: https://stackoverflow.com/a/35674625/3730626 – M B Jun 27 '22 at 05:36
-
I managed to figure the Gateway out, but now where do I put the ServerPinger file? The same folder as the Gateway starter? – Dre Jun 27 '22 at 11:52
-
In the same way the answerer has instantiated a class called `myTest`, you need to instantiate `ServerPinger`. For that, they need to be in the same package, and therefore, the same folder. One thing to note is that the methods in `ServerPinger` are static and don't require the class to be instantiated to call it. – M B Jun 28 '22 at 04:32
-
java_object = gateway.jvm.mypackage.ServerPinger() TypeError: 'JavaPackage' object is not callable – Dre Jun 28 '22 at 11:17
-
You probably also need to use the `java_import` method: https://stackoverflow.com/a/66889384/3730626 – M B Jun 28 '22 at 11:37
-
That ended up not being the issue. I fixed it though. So now what do I do? Print the return_object? Also, can I replace "address" in java_object.ping("address") with the IP I want to ping? – Dre Jun 30 '22 at 07:07
-
That depends on how the `ping` method works. You can place a breakpoint in the return statement and look into the object that gets returned and see where the data you wants can be found – M B Jun 30 '22 at 09:02
1
A better approach would be to use RESTful APIs for communication between multiple applications.

Gokul Nath KP
- 15,485
- 24
- 88
- 126