Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

Process p = Runtime.getRuntime().exec("python yourapp.py");

You can read up on how to actually read the output from this resource: http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

public class JavaRunCommand {

    public static void main(String args[]) {

        String s = null;

        try {
            
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("ps -ef");
            
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            
            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
            
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

Answer from Sevas on Stack Overflow
🌐
GitHub
github.com › devlpr › javathon
GitHub - devlpr/javathon: How to run python scripts in Java · GitHub
How to run python scripts in Java. Contribute to devlpr/javathon development by creating an account on GitHub.
Author   devlpr
🌐
GitHub
github.com › johnhuang-cn › jpserve
GitHub - johnhuang-cn/jpserve: Calling Python from JAVA
// init the PyServeContext, it will make a connection to JPServe PyServeContext.init("localhost", 8888); // prepare the script, and assign the return value to _result_ String script = "a = 2\n" + "b = 3\n" + "_result_ = a * b"; // sned the script to PyServe, it returns the final result PyResult rs = executor.exec(script); // check if the execution is success if (rs.isSuccess()) { System.out.println("Result: " + rs.getResult()); // get the _result_ value } else { System.out.println("Execute python script failed: " + rs.getMsg()); } ------------------------ Result: 6 · File f = new File("src/test/java/net/xdevelop/jpclient/test/helloworld.py"); PyResult rs = PyServeContext.getExecutor().exec(f); InputStream in = ClientSample.class.getResourceAsStream("helloworld.py"); PyResult rs = PyServeContext.getExecutor().exec(in);
Starred by 59 users
Forked by 18 users
Languages   Java 58.0% | Python 42.0% | Java 58.0% | Python 42.0%
🌐
GitHub
github.com › FlorianWilhelm › coffee_snake
GitHub - FlorianWilhelm/coffee_snake: Run a Python script within Java · GitHub
This was only tested on Linux with Python 3.5. In the coffee snake repo create a virtual environment with virtualenv venv. Then activate with source venv/bin/activate followed by pip install jep numpy pandas scipy sckit-learn.
Author   FlorianWilhelm
🌐
Robert Peng's Blog
mr-dai.github.io › embedding-jython
Embedding Python in Java using Jython - Robert Peng's Blog
September 10, 2018 - Reusing PythonIntrepreter is simple: just hold it somewhere in your program as a singleton. You can implement this singleton pattern in any way you like: Spring Application Context, double-check locking, you name it. We will just make it a private static final variable here: It’s a bit trickier to avoid invoking PythonInterpreter.eval, as it is the only method we can use to run designated Python code and get its result. Groovy provides GroovyShell.parse, which takes a Groovy script as input and returns a Script instance.
Top answer
1 of 10
82

Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

Process p = Runtime.getRuntime().exec("python yourapp.py");

You can read up on how to actually read the output from this resource: http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

public class JavaRunCommand {

    public static void main(String args[]) {

        String s = null;

        try {
            
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("ps -ef");
            
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            
            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
            
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

2 of 10
36

You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.

Jython does offers support for JSR-223 which basically lets you run a Python script from Java.

You can use a ScriptContext to configure where you want to send your output of the execution.

For instance, let's suppose you have the following Python script in a file named numbers.py:

for i in range(1,10):
    print(i)

So, you can run it from Java as follows:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here
    
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();
    
    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

And the output will be:

1
2
3
4
5
6
7
8
9

As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.

🌐
Coderanch
coderanch.com › t › 725750 › languages › Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
Hi Simon, Python has a concept of a "virtual environment" for pulling together all the requirements needed for running a nontrivial program. This is roughly similar to a java jar file being used to hold all the libraries needed for a nontrivial Java program. Explaining how to set up a Python virtual environment is beyond what can be explained here so please search for "Python virtual environment", "virtualenv", and "Python activate" for that information. Once the virtual environment is set up and tested, Java will probably need to use a shell script to invoke it.
🌐
GitHub
gist.github.com › n3rada › 0610814a846c379c2148e47c36b4fabe
Run Java Code From Python3 · GitHub
This feature simplifies the process for small programs or scripts by implicitly compiling and running the Java code in one step.
Find elsewhere
🌐
GitHub
github.com › laffra › pava
GitHub - laffra/pava: Run Java in Python · GitHub
Of course, the Python VM needs to be instructed where to find the Java class files. This is done by informing pava of the classpath to use: import pava pava.set_classpath(['...the location of the Java classfiles...']) Pava execution happens in two phases. In the first phase, before anything really runs, the Java classpath is processed and classfiles are transpiled.
Author   laffra
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Clone this repository at <script src="https://gist.github.com/zhugw/8d5999a3b2f6aef3ca21f53ca82d054c.js"></script> Save zhugw/8d5999a3b2f6aef3ca21f53ca82d054c to your computer and use it in GitHub Desktop. Download ZIP · Java invoke python script ·
🌐
Medium
medium.com › geekculture › how-to-execute-python-modules-from-java-2384041a3d6d
How To Execute Python Modules From Java | by Galina Blokh | Geek Culture | Medium
July 14, 2022 - One of the working solutions is to run this service in docker. Or we can find another, more effective production-friendly solution: to execute python code directly from Java code via the Jep library (Java Embedded Python). Down below are some citations from their FAQ on GitHub :
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - In this tutorial, we’ve learned about some of the most popular technologies for calling Python code from Java. The code backing this article is available on GitHub.
🌐
YouTube
youtube.com › codingnomads
How To Write and Run Applications in Java and Python (+ Git & GitHub!) - YouTube
In this tutorial, you'll learn how to write and run applications in Java and Python. We'll also cover how to configure your computer to write software progra...
Published   December 9, 2019
Views   1K
🌐
Jython
jython.org
Home | Jython
The Jython project provides ... of running on the JVM and access to classes written in Java. The current release (a Jython 2.7.x) only supports Python 2 (sorry). There is work towards a Python 3 in the project’s GitHub repository. Jython implementations are freely available for both commercial and non-commercial use. They are distributed with source code under the PSF License v2. Jython is complementary to Java and is especially suited for the following tasks: Embedded scripting - Java programmers ...
🌐
GitHub
github.com › topics › python-script
python-script · GitHub Topics · GitHub
java mock docker framework spring spring-boot continuous-integration python-script mockito junit spring-security junit5 mockmvc ... Repo contains a project to run a springboot api using shell & python scripts invoked by another spring boot application inside a docker container
🌐
Delft Stack
delftstack.com › home › howto › java › call python script from java code
How to Call Python Script From Java Code | Delft Stack
February 2, 2024 - We can do that using Process, ProcessBuilder, and Jython. Let’s see how we can use each of them below. We can use the Process class of Java to run Python scripts from our Java code.
🌐
Reddit
reddit.com › r/java › best way to combine python and java?
r/java on Reddit: Best way to combine Python and Java?
October 29, 2022 -

My project uses some packages that are available only in Python and heavily rely on C libraries. The project also greatly benefits from Java libraries and the JVM. What's the optimal way to call Python functions from Java?

I tried:

  1. Small web-services: overhead to serialize data, start and stop the services. Also debugging is harder and implementing each new function is now double the effort.

  2. Jpy: a library that runs an interpreter in the JVM. Spare the service start/stop, but: isn't really feasible for more than a single-liner, data translation between Java and Python is cumbersome, and I also encountered runtime segmentation fault errors.

Any other options?

The project is in the machine-learning domain, so involves exchanging large numeric arrays and text. In some cases the execution switches back and forth between the platforms.

🌐
The SW Developer
theswdeveloper.com › post › java-python-jep
How to execute Python code in Java - The SW Developer
September 10, 2021 - Inject a String argument which will be used by the Python code: Our Python script argument named user_name will get the value of our Java code name variable. ... That's it. It's as simple as that.
🌐
Quora
quora.com › How-do-I-call-Python-script-from-Java
How to call Python script from Java - Quora
Answer (1 of 4): The old approach. [code]Process p = Runtime.getRuntime().exec("python yourapp.py"); [/code]You can read up on how to actually read the output here: http://www.devdaily.com/java/edu/pj/pj010016 There is also an Apache library (the Apache exec project) that can help you with thi...
🌐
Quora
quora.com › How-do-I-execute-a-python-file-with-Java
How to execute a python file with Java - Quora
Answer (1 of 4): Java and Python are different languages, so I could give you simple dismissive answer like… You don’t. But that would be wrong, because you could use Jython [1] from within Java to run Python scripts. Or, you could use something like… [code]Runtime.getRuntime().exec("python3 ...