我正在尝试使用jython在java中执行我的python脚本。重要的是,我需要使用jython将命令行参数传递给我的脚本,例如myscript.py arg1 arg2 arg3。这里有一个类似的问题:Passing arguments to Python script in Java
没有完全回答(所有的解决方案都不起作用)。
我的代码现在看起来像这样:
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。
发布于 2016-03-29 23:18:03
同时,我找到了一个解决方案。这就是它:
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);我需要做的只是将我的脚本作为arg0添加到传递的参数中!
发布于 2016-03-29 22:16:11
下面是实现这一点的一小段代码:
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 arg3https://stackoverflow.com/questions/36286653
复制相似问题