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]{{ ...
Discussions

Java ProcessBuilder not able to run Python script in Java - Stack Overflow
My recommendation was only to see ... stream immediately after creating your ProcessBuilder object, you're following my recommendations. Then something else might be wrong. How do you run your python script if you weren't using Java?... More on stackoverflow.com
🌐 stackoverflow.com
java - Process Builder error while running Python script by passing arguments - Stack Overflow
I have one Python script to run using java ProcessBuilder. Python script requires 2 arguments. More on stackoverflow.com
🌐 stackoverflow.com
How to execute a python file with some arguments in java - Stack Overflow
Then ignore it refers to exec and use a ProcessBuilder to create the process. Also break a String arg into String[] args to account for things like paths containing space characters. ... This May Be Helpful ! You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable. #!/usr/bin/python import sys print 'Number of Arguments... More on stackoverflow.com
🌐 stackoverflow.com
March 19, 2018
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
🌐
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....
🌐
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.

🌐
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 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 &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 ​
🌐
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
Find elsewhere
🌐
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.
🌐
GitHub
gist.github.com › zhugw › 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script · GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
🌐
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.
Top answer
1 of 4
2
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.#!/usr/bin/python import sys print ('Number of Arguments:', len(sys.argv), 'arguments.') print ('Argument List:', str(sys.argv)) print('This is Python Code') print('Executing Python') print('From Java')if you save the above file as script_python and then set the execution permissions usingchmod 777 script_pythonThen you can call this script from Java Runtime.exec() like belowimport java.io.*; import java.nio.charset.StandardCharsets; public class ScriptPython { Process mProcess; public void runScript(){ Process process; try{ process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"}); mProcess = process; }catch(Exception e) { System.out.println("Exception Raised" + e.toString()); } InputStream stdout = mProcess.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8)); String line; try{ while((line = reader.readLine()) != null){ System.out.println("stdout: "+ line); } }catch(IOException e){ System.out.println("Exception in reading output"+ e.toString()); } } } class Solution { public static void main(String[] args){ ScriptPython scriptPython = new ScriptPython(); scriptPython.runScript(); } }Hope this helps and if not then its recommended to join our Java training class and learn about Java in detail.
2 of 4
0
There are three ways to get this done:runtime approachprocess approachjython approachHave a look at this blog for detailed explanation with example.
🌐
Stack Overflow
stackoverflow.com › questions › 47081080 › how-can-i-execute-python-script-via-terminal-in-java
how can i execute python script via terminal in Java - Stack Overflow
When you pass a string in ... you should use a String[] with the path of your executable ( '/python3/python.exe' or 'python' or 'py') followed by the path of your script, followed by the arguments....
🌐
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....
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);