如何使用jython将参数传递给java中的python脚本

我试图使用jython在java中执行我的python脚本。 重要的是我需要使用jython将命令行参数传递给我的脚本,例如myscript.py arg1 arg2 arg3。 这里有一个类似的问题: 在Java中将参数传递给Python脚本

没有完全回答(没有一个解决方案有效)。

我的代码现在看起来像这样:

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

但是,这似乎没有传递给python脚本的任何参数。 有任何建议如何正确吗? 它必须简单,但我在网上找不到任何文档。

我使用的是python 2.7和jython 2.7.0。

与此同时,我找到了解决方案。 这里是:

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

我需要做的只是将我的脚本添加到传递的参数arg [0](参见代码的第一行)!

这里有一个小代码:

 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(); } } } 

这会在目录/ path / to / script中调用一个名为myscript.py的python脚本。

myscript.py的一个例子:

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