简体   繁体   English

将数据从 java 传递到 python 并返回 jython

[英]pass data from java to python and back jython

I am using Jython to run a python script from Java.我正在使用 Jython 从 Java 运行 python 脚本。 I am able to send data to the python script as command line arguments when I invoke the script using a PythonInterpreter .当我使用PythonInterpreter调用脚本时,我能够将数据作为命令行参数发送到 python 脚本。

Now I want to call a Java method from within the Jython script, passing a List as a method argument.现在我想从 Jython 脚本中调用一个 Java 方法,将一个List作为方法参数传递。 How do I do that?我怎么做?

I am posting code for both passing of data from Java -> Python and Python -> Java.我发布了从 Java -> Python 和 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().字符串数组“s”被传递给 python 脚本,“city”列表通过函数调用 getData() 从 python 传递给 Java。

JavaProg.java: Java程序.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:脚本.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!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM