Can anyone show me a working simple example (java + python code) of calling python script from java code by passing parameters and getting back the results?
Asked
Active
Viewed 1.0k times
3
-
this was the first result when I google it. http://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java – hcarrasko Dec 01 '14 at 19:03
-
I've already tried that, but the sample codes I've googled are not as simple I can understand, or simply not working. – elaspog Dec 01 '14 at 19:03
-
Already tried that. But "python.exec("number3 = number1+number2");" is not not a script beeing called. – elaspog Dec 01 '14 at 19:06
-
Ideally, since this is Java (you don't use Android, do you?), use Jython to run the script! – fge Dec 01 '14 at 19:07
1 Answers
5
Try using Java ScriptEngine
to run the code as Jython.
Sample program:
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);
}
}
You'll need to include the jython engine jar in your classpath. look for it here

Stav Saad
- 589
- 1
- 4
- 13