Using ProcessBuilder and Jython to Run Python Scripts from Java

To invoke Python code from Java, you can use several approaches, including using the Java ProcessBuilder to run Python scripts or integrating with libraries that support inter-language communication like Jython (for Python 2.x) or using a library such as Jep (Java Embedded Python). Here, I’ll outline the ProcessBuilder approach, which is straightforward and works with any Python version.

Method: Using ProcessBuilder

1. Prepare Your Python Script

Create a Python script that performs the desired task. Let’s assume you have a simple Python script named script.py:

# script.py
import sys

def main():
    if len(sys.argv) != 2:
        print("Usage: python script.py <argument>")
        sys.exit(1)
    
    argument = sys.argv[1]
    print(f"Hello from Python! Argument received: {argument}")

if __name__ == "__main__":
    main()

2. Write Java Code to Invoke Python Script

In your Java application, use ProcessBuilder to run the Python script. Here is an example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class PythonInvoker {

    public static void main(String[] args) {
        try {
            // Define the command to run the Python script
            List<String> command = new ArrayList<>();
            command.add("python"); // Use "python3" if needed
            command.add("path/to/your/script.py");
            command.add("your_argument");

            // Create a ProcessBuilder
            ProcessBuilder pb = new ProcessBuilder(command);
            
            // Start the process
            Process process = pb.start();

            // Read the output from the Python script
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            // Read the standard output
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // Read the standard error
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }

            // Wait for the process to complete
            int exitCode = process.waitFor();
            System.out.println("Process exited with code: " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Jython is an implementation of Python that runs on the Java platform. It allows you to seamlessly integrate Python and Java code. However, it’s important to note that Jython currently supports Python 2.x and not Python 3.x. Here’s how you can use Jython to run Python code from Java:

Setting Up Jython

  1. Download and Install Jython:
    • Download the Jython installer from the Jython website.
    • Install Jython by running the installer (java -jar jython-installer-version.jar).
  2. Add Jython to Your Project:
    • Add jython-standalone.jar to your project’s classpath. You can download the standalone JAR file from the Maven repository.

Example: Running Python Code from Java Using Jython

Python Code (Embedded in Java)

You can embed Python code directly in your Java program using Jython. Here’s a simple example:

import org.python.util.PythonInterpreter;
import org.python.core.*;

public class JythonExample {
    public static void main(String[] args) {
        // Create a Python interpreter
        PythonInterpreter pythonInterpreter = new PythonInterpreter();

        // Define Python code
        String pythonCode = 
            "def greet(name):\n" +
            "    return 'Hello, ' + name\n" +
            "\n" +
            "result = greet('World')\n";

        // Execute the Python code
        pythonInterpreter.exec(pythonCode);

        // Retrieve a variable from the Python code
        PyObject result = pythonInterpreter.get("result");

        // Print the result
        System.out.println(result.toString());

        // Closing the interpreter
        pythonInterpreter.close();
    }
}

Example: Using an External Python Script

If you prefer to run an external Python script, you can load and execute it using Jython:

External Python Script (script.py)

# script.py
def greet(name):
    return 'Hello, ' + name

result = greet('World')

Java Code to Run External Script

import org.python.util.PythonInterpreter;
import org.python.core.*;

public class JythonExample {
    public static void main(String[] args) {
        // Create a Python interpreter
        PythonInterpreter pythonInterpreter = new PythonInterpreter();

        // Set script file path
        String scriptPath = "path/to/your/script.py";

        // Execute the script
        pythonInterpreter.execfile(scriptPath);

        // Retrieve a variable from the Python code
        PyObject result = pythonInterpreter.get("result");

        // Print the result
        System.out.println(result.toString());

        // Close the interpreter
        pythonInterpreter.close();
    }
}

You may also like...