我想使用ScriptEngine从java调用python脚本,但我不确定如何添加参数
从命令行开始,它类似于:python test.py language 10 "some text"
其中语言,10,“某些文本”是用户将给出的参数。
以下是我要修改的一段代码(请参阅此answer)
StringWriter writer = new StringWriter(); //ouput will be stored here
ScriptEngineManager manager = new ScriptEngineManager();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer); //configures output redirection
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("test.py"), context);
System.out.println(writer.toString());
答案 0 :(得分:0)
通过documentation,似乎可以通过put()
来实现:
// rest of your code
ScriptEngine engine = manager.getEngineByName("python");
engine.put(ScriptEngine.ARGV, array_of_strings);
engine.eval(new FileReader("test.py"), context);
// rest of your code
其中array_of_strings
是要用作参数的字符串数组。