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...
🌐
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 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 & 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 ​
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - @Test public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception { ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py")); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); List<String> results = readProcessOutput(process.getInputStream()); assertThat("Results should not be empty", results, is(not(empty()))); assertThat("Results should contain output of script: ", results, hasItem( containsString("Hello Baeldung Readers!!"))); int exitCode = process.waitFor(); assertEquals("No errors should be detected", 0, exitCode); }
🌐
Stack Overflow
stackoverflow.com › questions › 38666226 › pass-command-line-arguments-to-python-via-processbuilder
Pass command line arguments to Python via ProcessBuilder - Stack Overflow
July 29, 2016 - CopyTraceback (most recent call last): File "InterWebApp.py", line 43, in <module> app.run() File "/usr/lib/python2.6/site-packages/web/application.py", line 313, in run return wsgi.runwsgi(self.wsgifunc(*middleware)) File "/usr/lib/python2.6/site-packages/web/wsgi.py", line 55, in runwsgi server_addr = validip(listget(sys.argv, 1, '')) File "/usr/lib/python2.6/site-packages/web/net.py", line 120, in validip raise ValueError, ':'.join(ip) + ' is not a valid IP address/port' ValueError: users.xml is not a valid IP address/port · Also, the script will not run with the argument in Java : CopyProcessBuilder pb = new ProcessBuilder("python", script.getAbsolutePath(), xml.getAbsolutePath()); Process p = pb.start();
🌐
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
Using sys library we can save arguments into String array in python file and get arguments into python file with the help of index based like sys.argv[0],sys.argv[1] and sys.argv[2].
🌐
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
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.

🌐
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.
Find elsewhere
🌐
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 - Yes, but I believe you are passing them wrong; unless your command line does look like python /directorypath/mypython.py "-A 'A Tool for binary' -c 1". A ProcessBuilder is not a shell interpreter! ... Okay, but even if i pass without these arguments [ ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py")] ; I again get the same "We need BeautifulSoup, sorry" error .
🌐
Stack Overflow
stackoverflow.com › questions › 50207465 › process-builder-error-while-running-python-script-by-passing-arguments
java - Process Builder error while running Python script by passing arguments - Stack Overflow
Can any one help me on this, how I can run this using java ProcessBuilder. ... Replaced with forward slashes but no luck same error. ... Save this answer. ... Show activity on this post. > only has special meaning in a shell, like cmd.exe. Currently, you are passing a very long filename which includes spaces and a > in it to Python.
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

🌐
Stack Overflow
stackoverflow.com › questions › 79921476 › building-a-process-with-processbuilder-from-a-py-script
python - Building a process with ProcessBuilder from a .py script? - Stack Overflow
When I try the filepath on it's own - i.e. ... = new ProcessBuilder(processPath); - I hit an IOException telling me said file is not a valid Win32 application. When I try following the file path with a "python" argument - i.e. new ProcessBuilder(processPath, "python"); OR new ProcessBuilder(List.of(processPath, "python")); - the same thing happens.
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);
🌐
Stack Overflow
stackoverflow.com › tags › processbuilder › hot
Hottest 'processbuilder' Answers - Stack Overflow
You need to specify your python path: run in your terminal: "which python3" ProcessBuilder builder = new ProcessBuilder("your/python/path/python3","main.py","-rd ",selectedFile.getAbsolutePath()); ... When using ProcessBuilder each element in the command is a separate argument.
🌐
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.