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.

🌐
Medium
medium.com › @chamlinid › integrate-java-and-python-code-bases-1c4819fe19da
Integrate Java and Python code bases | by Chamlini Dayathilake | Medium
February 14, 2025 - Create a ProcessBuilder instance in the Java code, with the path of the script file and required parameter values for the Python function. Start execution of the Python script in Java.
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
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 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
Java - How to call python classes using processbuilder - Stack Overflow
How do I call and execute python class methods from java. My current java code works, but only if I write: if __name__ == '__main__': print("hello") But I want to execute a class method, regar... More on stackoverflow.com
🌐 stackoverflow.com
August 30, 2017
🌐
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]{{ ...
🌐
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
Using ProcessBuilder API is more preferred approach than the Process. Best Open Source Business Intelligence Software Helical Insight is Here ... Hope the samples have helped you in getting some insights. ... call python script from java with arguments Can I call a Python function from 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 ​
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script · Raw · gistfile1.txt · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
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. For example, Thanks….
🌐
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
🌐
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 - I am trying to call a python script from Java. I am using ProcessBuilder to call the python script and it does work (sort of) It's very easy to call the python script on windows, by using the command 'python' which should point to the latest version of python.
Find elsewhere
🌐
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.
🌐
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:
🌐
Tabnine
tabnine.com › home page › code › java › java.lang.processbuilder
java.lang.ProcessBuilder java code examples | Tabnine
@Nullable public Process startInterpreter(String pythonExe) { Process p; try { ProcessBuilder builder = new ProcessBuilder(pythonExe, "-i", jsonizer); builder.redirectErrorStream(true); builder.redirectError(new File(parserLog)); builder.redirectOutput(new File(parserLog)); builder.environment().remove("PYTHONPATH"); p = builder.start(); } catch (Exception e) { _.msg("Failed to start: " + pythonExe); return null; } return p; } ... import java.io.IOException; public class CLS { public static void main(String...
🌐
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
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - It means if there a heavy err flow out during the batch, the ProcessBuilder will hang because execution is not done, so std ReadLine is not done, so stderr thread is not launched so it does not consume output from err so you are in a deadlock. Wouldn’t it Executors.newFixedThreadPool(2); better ? ... Hi, i am working on a javafx project it is typically a statistical application i am using python for the analysis and i wanted to include the python scripts into the javafx app so i wanted to use the process builder to do it Do u think it is efficient?
🌐
GitHub
github.com › Palak-B › java-python-processBuilder
GitHub - Palak-B/java-python-processBuilder
Toy code to connect Java and Python The above Java service runs a Python program using ProcessBuilder.
Author   Palak-B
🌐
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
🌐
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 ...
🌐
Tutorialspoint
tutorialspoint.com › java › lang › processbuilder_command_string.htm
Java ProcessBuilder command() Method
The Java ProcessBuilder command(String... command) method Sets this process builder's operating system program and arguments. This is a convenience method that sets the command to a string list containing the same strings as the command array, in
Top answer
1 of 3
2

So if I understand your requirement, you want to invoke a class method in pdfFileScraper.py. The basics of doing this from the shell would be something akin to:

scraper=path/to/pdfFileScraper.py
dir_of_scraper=$(dirname $scraper)
export PYTHONPATH=$dir_of_scraper
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()'

What we do is get the directory of pdfFileScraper, and add it to the PYTHONPATH, then we run python with a command that imports the pdfFileScraper file as a module, which exposes all the methods and classes in the class in the namespace pdfFileScraper, and then construct a class ClassInScraper().

In java, something like:

import java.io.*;
import java.util.*;

public class RunFile {
    public static void main(String args[]) throws Exception {
        File f = new File(args[0]); // .py file (e.g. bob/script.py)

        String dir = f.getParent(); // dir of .py file
        String file = f.getName(); // name of .py file (script.py)
        String module = file.substring(0, file.lastIndexOf('.'));
        String command = "import " + module + "; " + module + "." + args[1];
        List<String> items = Arrays.asList("python", "-c", command);
        ProcessBuilder pb = new ProcessBuilder(items);
        Map<String, String> env = pb.environment();
        env.put("PYTHONPATH", dir);
        pb.redirectErrorStream();
        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);
        }
    }
}
2 of 3
1

You can also call Python lib directly via JNI. This way, you don't start new process, you can share context between script calls, etc.

Take a look here for a sample:

https://github.com/mkopsnc/keplerhacks/tree/master/python