6

I am prototyping an interface to our application to allow other people to use python, our application is written in java. I would like to pass some of our data from the java app to the python code but I am unsure how to pass an object to python. I have done a simple java->python function call using simple parameters using Jython and found it very useful for what I am trying to do. Given the class below, how can I then use it in Python/Jython as an input to a function/class:

public class TestObject 
{
   private double[] values;
   private int length;
   private int anotherVariable;

   //getters, setters
 }
user1584120
  • 979
  • 1
  • 14
  • 30

3 Answers3

6

One solution. You could use some sort of message system, queue, or broker of some sort to serialize/deserialize, or pass messages between python and java. Then create some sort workers/producer/consumers to put work on the queues to be processed in python, or java.

Also consider checking out for inspiration: https://www.py4j.org/

py4j is used heavily by/for pyspark and hadoop type stuff.

To answer your question more immediately.

Example using json-simple.:

import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
 //import org.json.simple.JSONObject;
  

public class TestObject 
{
   private double[] values;
   private int length;
   private int anotherVariable;
   private boolean someBool;
   private String someString;

   //getters, setters

   public String toJSON() {
       JSONObject obj=new JSONObject();
       obj.put("values",new Double(this.values));
       obj.put("length",new Integer(this.length));
       obj.put("bool_val",new Boolean(this.SomeBool));
       obj.put("string_key",this.someString);
       StringWriter out = new StringWriter();
       obj.writeJSONString(out);
       return out.toString();
   }

   public void writeObject(){
          Writer writer = new BufferedWriter(
                              new OutputStreamWriter(
                                  new FileOutputStream("anObject.json"), "utf-8")
                              )
                           )

          writer.write(this.toJSON());
   }

   public static void setObject(){
       values = 100.134;
       length = 12;
       anotherVariable = 15;
       someString = "spam";
   }
 }

And in python:

class DoStuffWithObject(object):
    def __init__(self,obj):
        self.obj = obj
        self.changeObj()
        self.writeObj()

    def changeObj(self):
        self.obj['values'] = 100.134;
        self.obj['length'] = 12;
        self.obj['anotherVariable'] = 15;
        self.obj['someString'] = "spam";

    def writeObj(self):
        ''' write back to file '''
        with open('anObject.json', 'w') as f:
            json.dump(self.obj, f)

    def someOtherMethod(self, s):
       ''' do something else '''
       print('hello {}'.format(s))

import json
with open('anObject.json','r') as f:
    obj = json.loads(f.read())
# print out obj['values'] obj['someBool'] ...
for key in obj:
    print(key, obj[key])

aThing = DoStuffWithObject(obj)
aThing.someOtherMethod('there')

And then in java read back the object. There are solutions that exist implementing this idea (JSON-RPC, XML-RPC, and variants). Depending, you may may also want to consider using something like ( http://docs.mongodb.org/ecosystem/drivers/java/ ) the benefit being that mongo does json.

See:

A more comprehensive list of queues:

Resources referenced:

Community
  • 1
  • 1
jmunsch
  • 16,405
  • 6
  • 74
  • 87
  • thats pretty comprehensive thanks. So this writes the JSON to a file? Would that work with large arrays (many thousands multidimensional). – user1584120 May 12 '15 at 13:12
  • As @Clashsoft points out the code itself has errors. I generally don't program in java, and by generally I mean none. Apologies. But yes the idea is very much usable with thousands of arrays. However if it starts getting into a lot of objects being passed around, then you may want to consider how they are managed, hence the other resources that I have tried to link to. – jmunsch May 12 '15 at 13:17
0

Agree with the answer below. I think that the bottom line is that "Python and Java are separate interpreter-environments." You therefore shouldn't expect to transfer "an object" from one to the other. You shouldn't expect to "call methods." But it is reasonable to pass data from one to another, by serializing and de-serializing it through some intermediate data format (e.g. JSON) as you would do with any other program.

In some environments, such as Microsoft Windows, it's possible that a technology like OLE (dot-Net) might be usable to allow environments to be linked-together "actively," where the various systems implement and provide OLE-objects. But I don't have any personal experience with whether, nor how, this might be done.

Therefore, the safest thing to do is to treat them as "records," and to use serialization techniques on both sides. (Or, if you got very adventurous, run (say) Java in a child-thread.) An "adventurous" design could get out-of-hand very quickly, with little return on investment.

Mike Robinson
  • 7,537
  • 2
  • 17
  • 28
0

You need to make the python file to exe using py2exe , Refer the link : https://www.youtube.com/watch?v=kyoGfnLm4LA. Then use the program in java and pass arguements:

Please refer this link it will be having the details:

Calling fortran90 exe program from java is not executing

Community
  • 1
  • 1
Santhucool
  • 1,615
  • 2
  • 29
  • 77
  • yes, i saw that was an option to run it as a process, however this does not allow you to return anything – user1584120 May 13 '15 at 12:16
  • It will allow to return. You will catch the return value from exe in your java code and can control that for further things!!You can pass the values to your python code and using args[] argv[] you can take that!! – Santhucool May 13 '15 at 12:22
  • Do you mean like in System.exit(0) I can get a 0? Thats a single integer, I would normally be expecting an array or struct/class in the return. – user1584120 May 13 '15 at 12:25
  • I mean you can return what ever you need from your python code and using java you can catch that!! – Santhucool May 13 '15 at 12:27
  • I'm not sure I follow how to do that? Use the OutputStream? – user1584120 May 13 '15 at 12:51