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
Top answer
1 of 10
81

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.

🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - In this section, we’ll take a look at two different options we can use to invoke our Python script using core Java. Let’s first take a look at how we can use the ProcessBuilder API to create a native operating system process to launch python and execute our simple script:
Discussions

python - Running a .py file from Java - Stack Overflow
I am trying to execute a .py file from java code. I move the .py file in the default dir of my java project and I call it using the following code: String cmd = "python/"; String py = "fil... More on stackoverflow.com
🌐 stackoverflow.com
How to start a python process from Java and do IO communication?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
10
5
August 11, 2022
How can I call Python from Java?
How about using jni to write a c++ module that can run the python interpreter? Here is an api for using python interpreter from QML/JS: https://github.com/thp/pyotherside/blob/master/src/qpython.h . you can create a similar jni module for your java code: https://en.m.wikipedia.org/wiki/Java_Native_Interface More on reddit.com
🌐 r/learnprogramming
2
2
June 17, 2020
[Help]How to call Java .class methods in Python
Stay up to date with the latest news, packages, and meta information relating to the Python programming language. --- If you have questions or are new to Python use r/LearnPython ... I am working on a project where a I wrote a program in a in Java and made the GUI in python, buy now I want ... More on reddit.com
🌐 r/Python
5
0
March 11, 2023
🌐
pytz
pythonhosted.org › javabridge › java2python.html
Calling Python from Java — python-javabridge 1.0.12 documentation
import javabridge cpython = javabridge.JClassWrapper('org.cellprofiler.javabridge.CPython')() d = javabridge.JClassWrapper('java.util.Hashtable')() result = javabridge.JClassWrapper('java.util.ArrayList')() d.put("result", result) cpython.execute( 'import javabridge\n' 'x = { "foo":"bar"}\n' 'ref_id = javabridge.create_and_lock_jref(x)\n' 'javabridge.JWrapper(result).add(ref_id)', d, d) cpython.execute( 'import javabridge\n' 'ref_id = javabridge.to_string(javabridge.JWrapper(result).get(0))\n' 'assert javabridge.redeem_jref(ref_id)["foo"] == "bar"\n' 'javabridge.unlock_jref(ref_id)', d, d)
🌐
Coderanch
coderanch.com › t › 725750 › languages › Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
If you're going to use Runtime.exec() or one of the other external program execution resources, then you should actually use the absolute program path. That is "/usr/bin/python", not just "python". Don't depend on the JVM's shell path. You may also need to intercept the stdio paths for the python interpreter. If you just want to run a preset gnuradio from Java, that's probably it.
🌐
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 - Example of how to run python3.9 functions from Java Jep · The printouts will be the same as for the Python 3.8 version. That’s all folks!! In this tutorial, you got clear instructions on how to execute your Python code from any Java application for Python 3.8 and Python 3.9 versions.
🌐
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.
Find elsewhere
🌐
Helicaltech
helicaltech.com › blog › ways to execute python code from java - helical it solutions pvt ltd
Ways to Execute Python Code From Java - Helical IT Solutions Pvt Ltd
Big Data Consulting Services, Big Data Analytics - Helical IT solutions Pvt Ltd
In case if your project has requirement ... 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. ... Python code that is written in a file which can be executed using the Jython ScriptContext... Helical IT Solutions Pvt Ltd offers Jaspersoft consulting, Pentaho consulting, Talend consulting & big data consulting services. Helical IT Solutions Pvt Ltd, based out of Hyderabad India, is an IT company specializing in Data Warehousing, Business Intelligence and B
Rating: 4.4 ​
Top answer
1 of 4
2
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.#!/usr/bin/python import sys print ('Number of Arguments:', len(sys.argv), 'arguments.') print ('Argument List:', str(sys.argv)) print('This is Python Code') print('Executing Python') print('From Java')if you save the above file as script_python and then set the execution permissions usingchmod 777 script_pythonThen you can call this script from Java Runtime.exec() like belowimport java.io.*; import java.nio.charset.StandardCharsets; public class ScriptPython { Process mProcess; public void runScript(){ Process process; try{ process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"}); mProcess = process; }catch(Exception e) { System.out.println("Exception Raised" + e.toString()); } InputStream stdout = mProcess.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8)); String line; try{ while((line = reader.readLine()) != null){ System.out.println("stdout: "+ line); } }catch(IOException e){ System.out.println("Exception in reading output"+ e.toString()); } } } class Solution { public static void main(String[] args){ ScriptPython scriptPython = new ScriptPython(); scriptPython.runScript(); } }Hope this helps and if not then its recommended to join our Java training class and learn about Java in detail.
2 of 4
0
There are three ways to get this done:runtime approachprocess approachjython approachHave a look at this blog for detailed explanation with example.
🌐
GitHub
github.com › devlpr › javathon
GitHub - devlpr/javathon: How to run python scripts in Java · GitHub
How to run python scripts in Java. This project will build a JNI interface that loads up a Python interpreter and then executes the simple Python script through the JVM.
Author   devlpr
🌐
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 - Create a process to run the ProcessBuilder using the start() method; this will execute the Python script. Create a BufferedReader to get the output of the Python script from the process.
🌐
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...
🌐
YouTube
youtube.com › watch
Execute a python script with few arguments in java | Pass Arguments to Python script using java - YouTube
In this video we learn Execute a python file with few arguments in java , pass arguments using ProcessBuilder class, using process builder class we can execu...
Published   June 5, 2021
🌐
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 ...
🌐
Reddit
reddit.com › r/javahelp › how to start a python process from java and do io communication?
r/javahelp on Reddit: How to start a python process from Java and do IO communication?
August 11, 2022 -

I'm a python dev, like I know literally no Java. But because I'm experienced in python I can at least kinda understand what I'm doing in Java. But I'm stuck on this. I know it's basic shit, I can do this in python, but I just can't read the language so I can't read any help or guides either.

All I need to do really is start a python program from Java as a subprocess, receive it's output stream and be able to send to its input stream.

The python program is a discord bot using async/await stuff and will run continuously so it needs to be uninterrupted, like if it was run from the terminal EXCEPT the Java program can send input and receive output.

I also suck att processes and stuff (this is on Windows btw) and as I said I suck at Java too so sorry if I gave to little information or something. Just tell me if that's the case.

Thanks in advance :D

Top answer
1 of 5
3
just use some sort of medium where python or java reads/writes to say a .json file. To run things on your machine using java you can use https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String) Runtime.exec(String); where the String is some system dependent command (like a command line for windows, if you can start a python script from cmd you can use Runtime.exec to run the script) You can get the Process object https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html from that Runtime.exec call it returns a Process object. I've not gone this deep into the Process class but according to the docs: By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock. Where desired, subprocess I/O can also be redirected using methods of the ProcessBuilder class.
2 of 5
3
You can spawn a thread to consume the output stream of the process and similarly you can provide a thread to which you can supply input to feed to the process. I'd consider using ProcessBuilder to make it tidier, than Runtime.exec, to work with any arguments, redirection and environment - otherwise you're manipulating the commandline directly (with all of the escaping considerations). Starting a Process with ProcessBuilder will then let you access the IO and pass them to producer / consumer threads as appropriate.
🌐
TutorialsPoint
tutorialspoint.com › jython › jython_java_application.htm
Jython - Java Application
The following code block is a Java program having an embedded Jython script hello.py.usingexecfile() method of the PythonInterpreter object. It also shows how a Python variable can be set or read using set() and get() methods. import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, world from Java"); interp.execfile("hello.py"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye "); } }
🌐
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%
🌐
Codingdeeply
codingdeeply.com › home › call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
February 23, 2024 - One common approach is to use the ProcessBuilder class to call the Python interpreter and pass the script name as an argument. This method is simple but may not be suitable for complex scenarios.
🌐
Quora
quora.com › How-can-I-run-Python-code-in-Java-code-and-vice-versa
How to run Python code in Java code, and vice versa - Quora
Three-way to possible code intercept both languages 1. Runtime approach – Developer can run the Python program using the “exec” method in the Runtime class. Examole [code]Process p = Runtime.getRuntime().exec("python http://test1.py "+n...
🌐
my tiny TechBlog
norwied.wordpress.com › 2012 › 03 › 28 › call-python-script-from-java-app
call python script from Java app – my tiny TechBlog
June 1, 2018 - Basically we execute the python script by envoking python2.6 and provide the path to the script as parameter, as you would normally do it if you exec the script in a terminal/bash.