2016-05-04 110 views
2

參數Python腳本,我想打電話給使用的ScriptEngine的java python腳本,但我不知道如何添加參數呼叫與從Java

從命令行是一樣的東西: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

你也可以通過'Process p = Runtime.getRuntime()。exec(「python test.py language 10 \」some text \「」);''來實現,如http://stackoverflow.com/questions/17756721 /調用-python-from-java-tomcat6-as-sub-process –

+0

感謝您的評論。是的,我知道,但我不知道是否可以使用腳本引擎完成。 – Daisy

回答

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是一個用作參數的字符串數組。

+0

感謝您的回答,我嘗試過,但它會拋出NullPointerException – Daisy

+0

@Daisy哪個變量爲空? – DeepSpace

+0

它反駁了這一行:engine.put(ScriptEngine.ARGV,array_of_strings); – Daisy