Backend Development 3 min read

Running a Python Script from Java Using Runtime.exec and Jython

This article explains how to invoke a Python script from a Java program, pass arguments, retrieve output, and compares two approaches: using the Jython library for seamless JVM integration and the simpler Runtime.getRuntime().exec method for quick execution.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Running a Python Script from Java Using Runtime.exec and Jython

The author needed to execute a Python script from Java, pass parameters to it, and optionally capture some results back into the Java program for further processing.

At first, the idea was to use jython.jar , a Java‑based implementation of Python that runs on any JVM, offering seamless integration between Java and Python code. After exploring the library, the author kept it as a backup solution because it is powerful but adds extra overhead.

Seeking a faster and simpler solution, the author discovered Java's Runtime class. The Runtime instance, obtained via Runtime.getRuntime() , can execute system commands directly, making it easy to run external scripts.

Runtime.getRuntime().exec("python /path/to/script.py arg1 arg2"); In this command the arguments are separated by spaces; the Python script can read them using sys.argv . To return data to Java, the script simply prints the desired output to the console, and the Java program reads the process’s input stream.

With this approach the problem is solved, while the author notes that many more advanced techniques exist for deeper language integration and encourages further exploration.

JavaPythoninterprocess communicationJythonRuntime.exec
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.