How to Run Python Code on Java Running Python code inside a Java application bridges the gap between Java’s enterprise-grade reliability and Python’s dominant ecosystem for machine learning, data science, and scripting. Modern software architectures frequently require both languages to coexist. Instead of maintaining completely separate microservices, developers can use several direct integration pathways to execute Python code seamlessly within a Java Virtual Machine (JVM).
Depending on your Python version, dependency requirements, and performance needs, you can choose from four primary integration strategies. 1. GraalPy (Modern Native & Python 3.x Execution)
GraalPy is a high-performance Python 3 implementation built on GraalVM. It allows you to run pure Python code and native extensions (like NumPy) directly inside Java with minimal memory overhead and a built-in Just-In-Time (JIT) compiler. How to Implement It
Add the GraalVM SDK dependency to your project, then use the Polyglot Context API to execute Python scripts.
import org.graalvm.home.Version; import org.graalvm.polyglot.*; public class GraalPyExample { public static void main(String[] args) { // Create a polyglot context with Python enabled try (Context context = Context.newBuilder(“python”) .allowAllAccess(true) .build()) { // Execute inline Python code context.eval(“python”, “print(‘Hello from Python running inside Java!’)”); // Evaluate code and retrieve a result Value result = context.eval(“python”, “221”); System.out.println(“Result: ” + result.asInt()); } } } Use code with caution. 2. ProcessBuilder (The Universal OS Command Line Approach)
The safest and most isolated way to run any modern Python 3 script—including those utilizing complex libraries like PyTorch or TensorFlow—is to execute it as an external sub-process. Java’s ProcessBuilder handles the system-level execution and pipes data streams between the environments. How to Implement It
ProcessBuilder triggers your local system’s Python interpreter. You must actively read the input and error streams to prevent the process from hanging.
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ProcessBuilderExample { public static void main(String[] args) { try { List Use code with caution. 3. JEP (Java Embedded Python)
JEP (Java Embedded Python) uses the Java Native Interface (JNI) to embed a CPython interpreter directly into Java sub-threads. This is an ideal solution for heavy data passing because it keeps data processing local without IPC overhead. How to Implement It
JEP requires a local CPython installation and native library configurations. Inside your code, you use a SharedInterpreter to run scripts.
import jep.SharedInterpreter; import jep.JepException; public class JepExample { public static void main(String[] args) { // SharedInterpreter runs modern Python 3 scripts smoothly try (SharedInterpreter interpreter = new SharedInterpreter()) { interpreter.exec(“import sys”); interpreter.exec(“print(sys.version)”); // Set variables inside the Python context interpreter.set(“a”, 10); interpreter.set(“b”, 20); interpreter.exec(“result = a + b”); // Extract values back into Java Object result = interpreter.getValue(“result”); System.out.println(“Sum from Python: ” + result); } catch (JepException e) { e.printStackTrace(); } } } Use code with caution. 4. Jython (The Legacy Approach)
Jython compiles Python code directly into Java bytecode, allowing it to run natively on the JVM. However, Jython strictly supports only Python 2.7. It cannot run modern Python 3 libraries or C extensions like NumPy. It should only be used for managing older codebases. How to Implement It
Include the Jython dependency in your project and call the PythonInterpreter utility.
import org.python.util.PythonInterpreter; import org.python.core.PyObject; public class JythonExample { public static void main(String[] args) { try (PythonInterpreter interpreter = new PythonInterpreter()) { // Execute simple Python 2.7 syntax interpreter.exec(“print ‘Hello from Jython!’”); interpreter.set(“x”, 5); interpreter.exec(“y = x * 10”); PyObject y = interpreter.get(“y”); System.out.println(“Result: ” + y.toString()); } } } Use code with caution. Quick Comparison: Which Strategy Should You Use?
Using Cross-Language pipeline to run Python 3 code with Java SDK
Leave a Reply