Skip to content
Advertisement

Can I pass arguments from a Python program to a Java Program, and vice versa?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement