1

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?

Perry
3,90326 gold badges40 silver badges51 bronze badges
asked Jun 26, 2022 at 6:06
0

2 Answers 2

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.

answered Jun 26, 2022 at 6:26
Sign up to request clarification or add additional context in comments.

8 Comments

There is an error. py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server (127.0.0.1:25333)
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: stackoverflow.com/a/35674625/3730626
I managed to figure the Gateway out, but now where do I put the ServerPinger file? The same folder as the Gateway starter?
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.
java_object = gateway.jvm.mypackage.ServerPinger() TypeError: 'JavaPackage' object is not callable
|
1

A better approach would be to use RESTful APIs for communication between multiple applications.

You can use Spring for Java, Flask for Python.

answered Jun 26, 2022 at 6:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.