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.

🌐
Coderanch
coderanch.com › t › 725153 › java › Java-process-builder-returning-correct
Java process builder not returning correct (or any) output (Java in General forum at Coderanch)
January 11, 2020 - In Java: (Note: for some reason in Java, 'python' -> python 2.7 even though it should be 3.8. That doesn't make any difference for my script anyway) The moment I run it from Java, the output I get is: Which is what I print when python isn't installed. But pretty clearly above, python 3 is installed. And that's why I say "[it almost] creates a whole new Mac OS with nothing installed". In python I use the 'subprocess' which is basically process builder.
Discussions

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
Running a python code using process builder Java - Stack Overflow
I need some help. I am trying to run a python script called mantime.py from a directory. I've tried to google it and found several ways to do it. Yet, I still got 2 as the exit value, which I expec... More on stackoverflow.com
🌐 stackoverflow.com
java - Using ProcessBuilder to execute a python script with command line options - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
calling python method through java ProcessBuilder() - Stack Overflow
How can I call a method in a Python file using ProcessBuilder in java? My Python file has a class and three methods. Also, how can I set my python method params from ProcessBuilder? Here is my Jav... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 27955622 › java-python-using-processbuilder
Java/python using processBuilder - Stack Overflow
From your scenario, you are looking for inter process communication. You can achieve this using shared file. Your python script will write the output in text file, and your java program will read the same file.
🌐
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 - 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...
🌐
Helicaltech
helicaltech.com › blog › ways to execute python code from java
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 ​
🌐
Stack Overflow
stackoverflow.com › questions › 31225697 › running-a-python-code-using-process-builder-java
Running a python code using process builder Java - Stack Overflow
ProcessBuilder("/usr/bin/python","/Users/ab/Downloads/ManTIME/mantime.py","-ppp","test",inputDir.getAbsolutePath(),"i2b2"); pb.directory(/myToolsDir) java · python · bash · processbuilder · Share · Improve this question · Follow · edited Jan 14, 2021 at 8:15 ·
Find elsewhere
🌐
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-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]{{ python-command }} will be...
🌐
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 ...
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - cuz i am using itellij and i am facing problems with python inside intellij. ... What if I use waitFor(timeout, timeUnit) instead of waitFor()? Should I also call Process.destroy() after waitFor(timeout, timeUnit)? ... If you are using single thread process.waitFor()? current Thread block unit Destroy the process if you are using multiThread when process.destroy() process immediately destroy i hope this help your doubt ... could you please let me know if there is an existing OpenSource Java library which creates OS based tasks (task scheduler on windows, crontab on linux), reads the task execution history ?
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › ProcessBuilder.html
ProcessBuilder (Java Platform SE 8 )
April 21, 2026 - Java™ Platform Standard Ed. 8 ... This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the ...
🌐
ZetCode
zetcode.com › java › processbuilder
Java ProcessBuilder - creating processes in Java
May 1, 2025 - Learn how to create and manage operating system processes in Java using ProcessBuilder. This tutorial covers executing commands, handling process input/output, and optimizing system interactions in Java applications.
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-processbuilder-class-java
Java.lang.ProcessBuilder class in Java - GeeksforGeeks
January 14, 2022 - ProcessBuilder(List command): This constructs a process builder with the specified operating system program and arguments.
🌐
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: