how to pass arguments to python script in java usi

2019-03-04 09:16发布

问题:

I am trying to execute my python script in java using jython. The important thing is that I need to pass command line arguments to my script using jython, e.g. myscript.py arg1 arg2 arg3. There is a similar question here: Passing arguments to Python script in Java

Which was not answered completely (none of the solutions work).

My code now looks like this:

String[] arguments = {"arg1", "arg2", "arg3"}; 
PythonInterpreter.initialize(props, System.getProperties(), arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);

However, this does not seem to pass any arguments to the python script. Any suggestions how to do it properly? It must be simple, but I can't find any documentation on the web.

I am using python 2.7 and jython 2.7.0.

回答1:

In the meantime, I have found a solution. Here it is:

String[] arguments = {"myscript.py", "arg1", "arg2", "arg3"};
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);

What I needed to do was simply to add my script to the passed parameters as arg[0] (see the first line of the code)!



回答2:

Here a small code to do so:

import org.python.core.Py;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.__builtin__;
import org.python.util.PythonInterpreter;

public class JythonTest {

    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        String fileUrlPath = "/path/to/script";
        String scriptName = "myscript";
        interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n"+ "from "+scriptName+" import * \n");
        String funcName = "myFunction";
        PyObject someFunc = interpreter.get(funcName);
        if (someFunc == null) {
            throw new Exception("Could not find Python function: " + funcName);
        }
        try {
            someFunc.__call__(new PyString(arg1), new PyString(arg2), new PyString(arg3));
        } catch (PyException e) {
            e.printStackTrace();
        }
    }
}

this call a python script in directory /path/to/script which is called myscript.py.

an example of myscript.py:

def myscript(arg1,arg2,arg3):
    print "calling python function with paramters:"
    print arg1
    print arg2
    print arg3