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
🌐
GitHub
github.com › Palak-B › java-python-processBuilder
GitHub - Palak-B/java-python-processBuilder · GitHub
Toy code to connect Java and Python The above Java service runs a Python program using ProcessBuilder.
Author   Palak-B
🌐
GitHub
github.com › topics › process-builder
process-builder · GitHub Topics · GitHub
An AI-powered solution designed to enhance virtual negotiations and decision-making through real-time emotion analysis. javascript mysql python java jsp tensorflow websocket keras pytorch mvc-architecture servlet-jsp tailwindcss process-builder
🌐
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. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Sorry, my bad. There is a simple example in the wiki: https://github.com/ninia/jep/wiki/Getting-Started
🌐
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 ​
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.

🌐
Rdkcentral
wiki.rdkcentral.com › pages › viewpage.action
Invoking Python script from Java
This shared memory based approach achieves good computing performance, while providing the access to the entirety of CPython and Java libraries. This approach allows direct memory access between the two machines, implementation of Java interfaces in Python, and even use of Java threading. JPype user guide is available in this link : https://github.com/jpype-project/jpype/blob/master/doc/userguide.rst
🌐
GitHub
github.com › JetBrains › jdk8u_jdk › blob › master › src › share › classes › java › lang › ProcessBuilder.java
jdk8u_jdk/src/share/classes/java/lang/ProcessBuilder.java at master · JetBrains/jdk8u_jdk
* <p>When passing information to a Java subprocess, * <a href=System.html#EnvironmentVSSystemProperties>system properties</a> * are generally preferred over environment variables. * * @return this process builder's environment · * * @throws SecurityException ·
Author   JetBrains
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - 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 ? something similar to this Java API (this is not a finished project) https://github.com/martinodutto/windows-task-scheduler-api
🌐
GitHub
github.com › srisatish › openjdk › blob › master › jdk › src › share › classes › java › lang › ProcessBuilder.java
openjdk/jdk/src/share/classes/java/lang/ProcessBuilder.java at master · srisatish/openjdk
* <p>Modifying a process builder's attributes will affect processes · * subsequently started by that object's {@link #start()} method, but · * will never affect previously started processes or the Java process · * itself. * * <p>Most error checking is performed by the {@link #start()} method.
Author   srisatish
🌐
GitHub
github.com › openjdk-mirror › jdk7u-jdk › blob › master › src › share › classes › java › lang › ProcessBuilder.java
jdk7u-jdk/src/share/classes/java/lang/ProcessBuilder.java at master · openjdk-mirror/jdk7u-jdk
* <p>Modifying a process builder's attributes will affect processes · * subsequently started by that object's {@link #start()} method, but · * will never affect previously started processes or the Java process · * itself. * * <p>Most error checking is performed by the {@link #start()} method.
Author   openjdk-mirror
🌐
GitHub
github.com › topics › processbuilder
processbuilder · GitHub Topics
This project builds a library with classes which better handle running external programs using Java. ... This repo contains the custom utilities to support Automation framework. Please go through the readme file · docker yaml json kafka ...
🌐
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...
🌐
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
🌐
GitHub
github.com › AdoptOpenJDK › openjdk-jdk11 › blob › master › src › java.base › share › classes › java › lang › ProcessBuilder.java
openjdk-jdk11/src/java.base/share/classes/java/lang/ProcessBuilder.java at master · AdoptOpenJDK/openjdk-jdk11
March 2, 2019 - * <p>Modifying a process builder's attributes will affect processes · * subsequently started by that object's {@link #start()} method, but · * will never affect previously started processes or the Java process · * itself. * * <p>Most error checking is performed by the {@link #start()} method.
Author   AdoptOpenJDK
🌐
Rdkcentral
wiki.rdkcentral.com › spaces › RDK › pages › 238230223 › Approaches+Considered
Approaches Considered - RDK - RDK Central Wiki
Jython is the Python implementation ... dependency not available error during python script execution · The ProcessBuilder API can be used to create a native operating system process to launch python....
🌐
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:
🌐
GitHub
github.com › jdf › processing.py
GitHub - jdf/processing.py: Write Processing sketches in Python · GitHub
Write Processing sketches in Python. Contribute to jdf/processing.py development by creating an account on GitHub.
Starred by 1.7K users
Forked by 226 users
Languages   Python 69.1% | Java 26.3% | GLSL 3.7% | Shell 0.6% | Batchfile 0.2% | AppleScript 0.1%
🌐
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.