1

I am using Jython to run a python script from Java. I am able to send data to the python script as command line arguments when I invoke the script using a PythonInterpreter.

Now I want to call a Java method from within the Jython script, passing a List as a method argument. How do I do that?

NikhilS
  • 83
  • 2
  • 11

1 Answers1

3

I am posting code for both passing of data from Java -> Python and Python -> Java. Hope this helps someone !! In this, String array "s" is passed to python script and from python, "city" list is passed from python to Java through function call getData().

JavaProg.java:

import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;


public class JavaProg
{
    static PythonInterpreter interpreter;

   @SuppressWarnings("resource")
public static void main( String gargs[] )
   {
      String[] s = {"New York", "Chicago"};
      PythonInterpreter.initialize(System.getProperties(),System.getProperties(), s);
      interpreter = new PythonInterpreter();
      interpreter.execfile("PyScript.py");
      PyInstance hello = (PyInstance) interpreter.eval("PyScript" + "(" + "None" + ")");
   }

   public void getData(Object[] data)
   {
       for (int i = 0; i < data.length; i++) {
           System.out.print(data[i].toString());
    }

   }
}

PyScript.py:

import JavaProg
class PyScript:
    def __init__(self,txt):
        city = []
        for i in range(0,len(sys.argv)):
            city.append(str(sys.argv[i]))
        jObj = JavaProg()
        jObj.getData(city)
        print "Done!"
NikhilS
  • 83
  • 2
  • 11
  • Hi @nikhilS, I am trying this exact code.. But i am getting error ```` Exception in thread "main" Traceback (most recent call last): File "PyScript.py", line 1, in import JavaProg ImportError: No module named JavaProg ```` – Aksanth Dec 04 '21 at 00:07