我正在尝试使用 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。
请您参考如下方法:
同时,我找到了解决办法。在这里:
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] 添加到传递的参数中(参见代码的第一行)!
