Ways to Execute Python Code From Java

Posted on by By Nikhilesh, in Java, Javascript | 0

There are many ways to execute Python code from with in Java. In case if your project has requirement to
execute Python code from Java, here are few code samples that I have collected from Internet.

Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.

Ways to use Python in Java Code

1. Using Jython ScriptContext:

Python code that is written in a file which can be executed using the Jython ScriptContext.
The following snippet uses the file named numbers.py and gets the output printed to the standard out put in python.

     StringWriter writer = new StringWriter();
     ScriptEngineManager manager = new ScriptEngineManager();
     ScriptContext context = new SimpleScriptContext();
     context.setWriter(writer);
     ScriptEngine engine = manager.getEngineByName("python");
     engine.eval(new FileReader("/home/numbers.py"), context);
     System.out.println(writer.toString());

2. Second way of using Jython:

In this approach PythonInterpreter object using which we can execute Python code.

        Properties properties = System.getProperties();
	PythonInterpreter.initialize(properties, properties, new String[0]);
	PythonInterpreter interp = new PythonInterpreter();
	interp.set("firstName", args[0]);
	interp.set("lastName", args[1]);
	interp.execfile("/home/numbers.py");

Another way of using PythonInterpreter

Using python code directly in the Java Programs. Here the python code is executed using the python interpreter written in Java.

        PythonInterpreter python = new PythonInterpreter();
	int number1 = 10;
	int number2 = 32;
	python.set("number1", new PyInteger(number1));
	python.set("number2", new PyInteger(number2));
	python.exec("number3 = number1 + number2");
	PyObject number3 = python.get("number3");
	System.out.println("Val : " + number3.toString());

3. Invoking native python interpreter using Java:

Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.

Using Runtime class or ProcessBuilder class of Java we can invoke the python interpreter directly
and pass the file that consists of the python code as an argument.
Here one should have Python installed on their machine and be available in the PATH.

      Process process = Runtime.getRuntime().exec("python numbers.py " + number1 + " " + number2);//OR
      ProcessBuilder builder = new ProcessBuilder("python", "test1.py", " " + number1, " " + number2);

Using ProcessBuilder API is more preferred approach than the Process.

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

Hope the samples have helped you in getting some insights.

Thanks,
Rajasekhar

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments