how to pass arguments to python script in java using jython

后端 未结 2 612
南旧
南旧 2021-01-25 08:54

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

相关标签:
2条回答
  • 2021-01-25 09:07

    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
    
    0 讨论(0)
  • 2021-01-25 09:12

    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)!

    0 讨论(0)
提交回复
热议问题