2014-12-01 88 views
3

任何人都可以通过传递参数和返回结果来显示一个从java代码调用python脚本的简单工作例子(java + python代码)吗?通过传递参数和结果从Java调用Python代码

+0

这是第一个结果,当我谷歌它。 http://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java – HCarrasko 2014-12-01 19:03:29

+0

我已经尝试过了,但我使用的代码示例并不是那么简单,我可以理解,或根本不工作。 – user1802693 2014-12-01 19:03:43

+0

已经尝试过。 但是“python.exec(”number3 = number1 + number2“);”不是一个叫做的脚本。 – user1802693 2014-12-01 19:06:12

回答

4

尝试使用Java ScriptEngine将代码作为Jython运行。

样例程序:

import javax.script.ScriptEngine; 
import javax.script.ScriptEngineManager; 
import javax.script.ScriptException; 

public class Main { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws ScriptException { 
     ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); 

     // Using the eval() method on the engine causes a direct 
     // interpretataion and execution of the code string passed into it 
     engine.eval("import sys"); 
     engine.eval("print sys"); 

     // Using the put() method allows one to place values into 
     // specified variables within the engine 
     engine.put("a", "42"); 

     // As you can see, once the variable has been set with 
     // a value by using the put() method, we an issue eval statements 
     // to use it. 
     engine.eval("print a"); 
     engine.eval("x = 2 + 2"); 

     // Using the get() method allows one to obtain the value 
     // of a specified variable from the engine instance 
     Object x = engine.get("x"); 
     System.out.println("x: " + x); 
    } 

} 

你需要在你的classpath中的Jython引擎罐子。寻找它here