Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default

package text_clustering;

import java.io.*;

public class Similarity {

    /**
     * 
     * @param args
     * 
     */
    public static void main(String[] args){
        try{
            String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
            //String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
            ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
            Process p = pb.start();

            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            System.out.println("Running Python starts: " + line);
            int exitCode = p.waitFor();
            System.out.println("Exit Code : "+exitCode);
            line = bfr.readLine();
            System.out.println("First Line: " + line);
            while ((line = bfr.readLine()) != null){
                System.out.println("Python Output: " + line);


            }

        }catch(Exception e){System.out.println(e);}
    }

}
Answer from shazin on Stack Overflow
Top answer
1 of 5
3

Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default

package text_clustering;

import java.io.*;

public class Similarity {

    /**
     * 
     * @param args
     * 
     */
    public static void main(String[] args){
        try{
            String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
            //String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
            ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
            Process p = pb.start();

            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            System.out.println("Running Python starts: " + line);
            int exitCode = p.waitFor();
            System.out.println("Exit Code : "+exitCode);
            line = bfr.readLine();
            System.out.println("First Line: " + line);
            while ((line = bfr.readLine()) != null){
                System.out.println("Python Output: " + line);


            }

        }catch(Exception e){System.out.println(e);}
    }

}
2 of 5
0

Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.

I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.

🌐
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
There are many ways to execute Python code from with in Java. In case if your project has requirement to execute Python code from Java, here are few code samples that I have collected from Internet. First way is using Jython: 3. Invoking native python interpreter using Java Helical IT Solutions Pvt Ltd offers Jaspersoft consulting, Pentaho consulting, Talend consulting &amp; 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 Big Data Analytics Services.
Rating: 4.4 ​
Discussions

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
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
Call and receive output from Python script in Java? - Stack Overflow
http://www.devdaily.com/java/java-exec-processbuilder-process-1 ... Sign up to request clarification or add additional context in comments. ... I have been thinking of making a workflow engine where the workflow functions would be python scripts and the engine it self a java based application. Would you know what would be the performance costs of continuously calling small python scripts one after another? 2016-05-18T03:58:41.293Z+00:00 ... Running ... More on stackoverflow.com
🌐 stackoverflow.com
Running python from Java using Process Builder - Stack Overflow
For an existing Java code that I want to extend, I need to run a python code from within Java. I am using Process builder for this: ProcessBuilder pb = new ProcessBuilder("python", "/directoryp... More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2016
🌐
Quora
quora.com › How-do-I-call-python-function-using-process-builder
How to call python function using process builder - Quora
Answer (1 of 2): [code]Process p = new ProcessBuilder("{{ python-command }}", "{{ arguments }}").start(); [/code]Your python file, file.py: [code]def foo(): //your prof def main(): if argv[0]=="foo": foo() if __name__ == "__main__": main() [/code]{{ ...
🌐
Wishusucess
wishusucess.com › home › blog › run python script in java using processbuilder
Python Script in Java Code Using ProcessBuilder - Wishusucess
June 7, 2020 - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadPython { public static void main(String[] args) throws IOException, InterruptedException { String path = "C:\Users\Admin\Desktop\pythoncodetest/script.py"; ProcessBuilder pb = new ProcessBuilder("python","C:\Users\Admin\Desktop\pythoncodetest/script.py").inheritIO(); Process p = pb.start(); p.waitFor(); BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = bfr.readLine()) != null) { System.out.println(line); } } } Step4 : – Run java code now to see the output in console.
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - Assuming we have a working Python installation when we run our script, we should see the message printed: ... 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:
🌐
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
🌐
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.
Find elsewhere
🌐
Medium
medium.com › @chamlinid › integrate-java-and-python-code-bases-1c4819fe19da
Integrate Java and Python code bases | by Chamlini Dayathilake | Medium
February 14, 2025 - Write a function inside a Python script and invoke the function inside the script itself. Use print(), to return values from the script. Create a ProcessBuilder instance in the Java code, with the path of the script file and required parameter ...
🌐
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. Print the output. Let’s implement the example in Java.
🌐
Google Groups
groups.google.com › g › jep-project › c › 6saaSk8VFz8
calling python machine learning code (keras) in java
Currently, I run the python scripts in JAVA using processBuilder and converting the java array to string then feeding it to python within the processBuilder, but I am limited on the size of the string.
🌐
Edureka Community
edureka.co › home › community › categories › java › how to run python script in java
How to run python script in java | Edureka Community
August 22, 2019 - 55415/how-to-run-python-script-in-java · You can use Java Runtime.exec() to run python script, ...READ MORE
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.

🌐
Stack Overflow
stackoverflow.com › questions › 35685056 › running-python-from-java-using-process-builder
Running python from Java using Process Builder - Stack Overflow
April 1, 2016 - I am using Process builder for this: ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py"); Process p=pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader ...
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.