Pass two separate arguments to ProcessBuilder instead of concatenating --arg1 and argumentValue:

ProcessBuilder builder = new ProcessBuilder("C:\\Python33\\python.exe",
                                            "-u",
                                            "C:\\...\\script.py,
                                            "--arg1",
                                            "argumentValue");

Otherwise the program to be executed will see a single argument --arg1 argumentValue that it does not recognise.

Answer from hmjd on Stack Overflow
🌐
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...
🌐
Blogger
learn-selenium-automation-testing.blogspot.com › 2021 › 06 › how-to-call-a-python-script-with-arguments-from-java-class.html
Learn Selenium Automation Testing: How to Call a Python Script with Arguments from Java class
In this post you will learn How ... file and provide multiple arguments in string format. To run ProcessBuilder class will use Process interface with start method....
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - In this first example, we’re ... in our test/resources folder. To summarize, we create our ProcessBuilder object by passing the command and argument values to the constructor....
🌐
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
🌐
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
Using Runtime class or ProcessBuilder class of Java we can invoke the python interpreter directly and pass the file that consists of the python code as an argument. Helical IT Solutions Pvt Ltd offers Jaspersoft consulting, Pentaho consulting, Talend consulting & 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 ​
🌐
Medium
medium.com › @chamlinid › integrate-java-and-python-code-bases-1c4819fe19da
Integrate Java and Python code bases | by Chamlini Dayathilake | Medium
February 14, 2025 - 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 values for the Python function.
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.

Find elsewhere
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
🌐
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.
🌐
Mar Java Mit Java
marjavamitjava.com › home › using processbuilder and jython to run python scripts from java
Using ProcessBuilder and Jython to Run Python Scripts from Java - Mar Java Mit Java
July 5, 2024 - import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class PythonInvoker { public static void main(String[] args) { try { // Define the command to run the Python script List<String> command = new ArrayList<>(); command.add("python"); // Use "python3" if needed command.add("path/to/your/script.py"); command.add("your_argument"); // Create a ProcessBuilder ProcessBuilder pb = new ProcessBuilder(command); // Start the process Process process = pb.start(); // Read the output from the Python script BufferedReader stdInput = new B
Top answer
1 of 2
9

When you spawn a process from another process, they can only (mostly rather) communicate through their input and output streams. Thus you cannot expect the return value from main33() in python to reach Java, it will end its life within Python runtime environment only. In case you need to send something back to Java process you need to write that to print().

Modified both of your python and java code snippets.

import sys
def main33():
    print("This is what I am looking for")

if __name__ == '__main__':
    globals()[sys.argv[1]]()
    #should be 0 for successful exit
    #however just to demostrate that this value will reach Java in exit code
    sys.exit(220)
public static void main(String[] args) throws Exception {       
        String filePath = "D:\\test\\test.py";      
        ProcessBuilder pb = new ProcessBuilder()
            .command("python", "-u", filePath, "main33");        
        Process p = pb.start(); 
        BufferedReader in = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
        StringBuilder buffer = new StringBuilder();     
        String line = null;
        while ((line = in.readLine()) != null){           
            buffer.append(line);
        }
        int exitCode = p.waitFor();
        System.out.println("Value is: "+buffer.toString());                
        System.out.println("Process exit value:"+exitCode);        
        in.close();
    }
2 of 2
1

You're overusing the variable line. It can't be both the current line of output and all the lines seen so far. Add a second variable to keep track of the accumulated output.

String line;
StringBuilder output = new StringBuilder();

while ((line = in.readLine()) != null) {
    output.append(line);
          .append('\n');
}

System.out.println("value is : " + output);
🌐
Rdkcentral
wiki.rdkcentral.com › display › RDK › Approaches+Considered
Invoking Python script from Java
Jython is the Python implementation ... to create a native operating system process to launch python. We can create our ProcessBuilder object passing the command and argument values to the constructor....
🌐
Stack Overflow
stackoverflow.com › questions › 29210255 › run-python-script-inside-java
run python script inside Java - Stack Overflow
There should be NO SPACES AT THE BEGGINING of every argument... tnxxxx ... Save this answer. ... Show activity on this post. Your command is built correctly but the way you pass it to ProcessBuilder isn't, as stated in its documentation you pass the args directly the way they are, there's no need to add spaces since the ProcessBuilder will take care of that for you. CopyProcessBuilder pb = new ProcessBuilder("c:\\Python27\\python", "c:\\probabilistic_cracker\\process.py","dic2.txt");
🌐
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.
🌐
Coderanch
coderanch.com › t › 717732 › languages › Python-Script-called-Java-class
Python Script gets called from a Java class (Jython/Python forum at Coderanch)
October 2, 2019 - Is your script executable? Do you have a shebang in your Python file? I just added it. Try using the full path to the script in the argument to exec.