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.

๐ŸŒ
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]{{ ...
Discussions

java - Using ProcessBuilder to execute a python script with command line options - Stack Overflow
in order to execute a python script(which has several command line parameters) from Java, I am trying to use is the following java code ยท String[] command = {"script.py", "run", "-arg1", "val1", "-arg2", "val2" , "-arg3" , "val_31 val_32", }; ProcessBuilder probuilder = new ProcessBuilder( ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Processbuilder to run Batch file and pythonscript - Stack Overflow
My requirement is i have to run Batch file located in (C:\Users\Vk\TestBatch.bat) under C:\users\VK\Logs(This is the path in which i have to run the batch file). After that i have to run the python script. I have to do this by using ProcessBuilder. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - running scripts through processbuilder - Stack Overflow
I'm trying to run Python, Ruby, C, C++, and Java scripts from a java program, and Processbuilder was suggested to me as a good way to run the scripts. From what I understand, Processbuilder mostly ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - ProcessBuilder cannot run python script with arguments - Stack Overflow
Ok, so I have a python script that I am running through ProcessBuilder. Everything is working fine. The issue I am having is whenever I pass arguments into the python script, the python script resp... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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 โ€‹
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
GitHub
gist.github.com โ€บ zhugw โ€บ 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script ยท GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/zhugw/8d5999a3b2f6aef3ca21f53ca82d054c.js&quot;&gt;&lt;/script&gt; Save zhugw/8d5999a3b2f6aef3ca21f53ca82d054c to your computer and use it in GitHub Desktop. Download ZIP ยท Java invoke python script ยท
๐ŸŒ
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:
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
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 50225795 โ€บ processbuilder-to-run-batch-file-and-pythonscript
java - Processbuilder to run Batch file and pythonscript - Stack Overflow
e. run python script using command `py <scriptName>` String [] command = {"cd C:\users\Vk", "TestBatch", "cd", "cd C:\Python27\ArcGIS10.3\", "py TestScript2.py"}; ProcessBuilder probuilder = new ProcessBuilder(command);
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
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
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 27955622 โ€บ java-python-using-processbuilder
Java/python using processBuilder - Stack Overflow
Good evening all, am running a python script inside java using processBuilder. the python script returns a list and i dont know how to get it java and use it since all i can do for the moment with process builder is print errors or outputs. is it possible to get the list in java as well.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55951323 โ€บ run-python-script-from-batchfile-doesnt-work-by-using-java-processbuilder
run python script from batchfile doesn't work by using java ProcessBuilder - Stack Overflow
@echo execute script @echo off cd\ d: cd Python27/ArcGISx6410.5 @echo Python Version python -V @echo start script python D:/<..>/my_py_file.py exit ... Because the code is embedded in groovy file running in tomcat. ... See also When Runtime.exec() won't for many good tips on creating and handling a process correctly. Then ignore it refers to exec and (continue to) use a ProcessBuilder to create the process. โ€“ Andrew Thompson Commented May 2, 2019 at 20:01 ... I think what's missing in your "run Python directly in JAVA" implementation is that you don't process the output after Process proc = pb.start();
๐ŸŒ
Raspberrypi
lb.raspberrypi.org โ€บ forums โ€บ viewtopic.php
Python Script from Java on Pi - Raspberry Pi Forums
February 19, 2014 - import java.io.*; import java.util.*; public class ProcessBuilderExample { public static void main(String args[]) throws IOException { ProcessBuilder pb = new ProcessBuilder("sudo", "python", "/home/pi/DropboxSync/Upload.py"); pb.redirectErrorStream(true); Process proc = pb.start(); Reader reader = new InputStreamReader(proc.getInputStream()); int ch; while ((ch = reader.read()) != -1) { System.out.print((char) ch); } reader.close(); } }