如何使用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
- 在编译器/机器级别执行什么操作?
- 如何在活动之间使用BottomNavigationView按下时突出显示项目?
- 如何在JavaFX中使用Spring?
- 从Java JHotDraw中重写的getActions在上下文菜单中创建子菜单
- Java File方法“canWrite()”可以支持锁定吗?
- 我如何学习使用Java commons-collections?
- 在Hibernate 3.2中使用连接池(c3p0-0.9.1.2)时,获取exception和应用程序无法与MySqL数据库连接?
- awt eventqueue 0 nullpointerexception错误
- 在Jersey2中使用@Immediate注释