You can use like this also:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

or

String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);

Run Python script from Java

Answer from Prateek on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - In this tutorial, we’ll take a look at some of the most common ways of calling Python code from Java. Throughout this tutorial, we’ll use a very simple Python script which we’ll define in a dedicated file called hello.py: ... Assuming we have a working Python installation when we run our ...
Discussions

Call and receive output from Python script in Java? - Stack Overflow
Because of this, would the easiest/most ... the script with runtime.exec, and then somehow capture printed output? Or, even though it would be very painful for me, I could also just have the Python script output to a temporary text file, then read the file in Java.... More on stackoverflow.com
🌐 stackoverflow.com
How to run Python file from java?
You can use GraalVM, and you can run python scripts using Runtime#exec or ProcessBuilder as if you were running from the terminal More on reddit.com
🌐 r/learnjava
5
27
June 23, 2020
Three ways to run Python programs from Java - Post.Byes
For example the page may want to forbid access to all file I/O and system interface commands. Cheers, Oralloy! ... this worked perfectly for me, but i’m facing another problem, if my python script throws any error like syntax error, the error message is not coming to my java output, i always have to run ... More on post.bytes.com
🌐 post.bytes.com
June 15, 2013
Execute python script through Java - Stack Overflow
I'm trying to run a very simple python script that clears and writes to a CSV file, from inside of java but I'm having a lot of trouble doing it. The scripts don't require any input and the output ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Coderanch
coderanch.com › t › 725750 › languages › Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
I am especially interested in solutions that might allow me to send commands to python (I hope to be able to change some variable values in the python on startup - not sure if this is at all possible). The Runtime.getRuntime().exec(command + param ) option might work for this, where "param" ...
🌐
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 - Let’s try to create a Python script and run it using Java code. Follow the steps below: Copy your Python script in a string in Java. Create a file with the .py extension using BufferedWriter.
Top answer
1 of 10
82

Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

Process p = Runtime.getRuntime().exec("python yourapp.py");

You can read up on how to actually read the output from this resource: http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

public class JavaRunCommand {

    public static void main(String args[]) {

        String s = null;

        try {
            
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("ps -ef");
            
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            
            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
            
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

2 of 10
36

You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.

Jython does offers support for JSR-223 which basically lets you run a Python script from Java.

You can use a ScriptContext to configure where you want to send your output of the execution.

For instance, let's suppose you have the following Python script in a file named numbers.py:

for i in range(1,10):
    print(i)

So, you can run it from Java as follows:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here
    
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();
    
    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

And the output will be:

1
2
3
4
5
6
7
8
9

As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.

🌐
pytz
pythonhosted.org › javabridge › java2python.html
Calling Python from Java — python-javabridge 1.0.12 documentation
class MyClass { static final CPython cpython = CPython(); public List<String> whereIsWaldo(String root) { ArrayList<String> result = new ArrayList<String>(); Hashtable locals = new Hashtable(); locals.put("result", result); locals.put("root", root); StringBuilder script = new StringBuilder(); script.append("import os\n"); script.append("import javabridge\n"); script.append("root = javabridge.to_string(root)"); script.append("result = javabridge.JWrapper(result)"); script.append("for path, dirnames, filenames in os.walk(root):\n"); script.append(" if 'waldo' in filenames:"); script.append(" result.add(path)"); cpython.exec(script.toString(), locals, null); return result; } } ... execute is a synonym for exec which is a Python keyword.
🌐
Medium
medium.com › geekculture › how-to-execute-python-modules-from-java-2384041a3d6d
How To Execute Python Modules From Java | by Galina Blokh | Geek Culture | Medium
July 14, 2022 - The lower the Python version and Jep library version you will take, the more complicated java syntax you will use (and vice versa). But latest JEP versions can readily execute JEP old versions’ syntax. In your system, it is mandatory to set up an environment variable. For macOSX, it will be like running in the terminal: export DYLD_LIBRARY_PATH="<your_user>/myenv/lib/python3.8/site-packages/jep"$DYLD_LIBRARY_PATH · And do not forget to add the same line to your ~/.zshrc file!
Find elsewhere
🌐
Quora
quora.com › How-do-I-execute-a-python-file-with-Java
How to execute a python file with Java - Quora
Answer (1 of 4): Java and Python are different languages, so I could give you simple dismissive answer like… You don’t. But that would be wrong, because you could use Jython [1] from within Java to run Python scripts. Or, you could use something like… [code]Runtime.getRuntime().exec("python3 ...
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
Three ways to run Python programs from Java - Post.Byes
June 15, 2013 - Or, hoisting is not reasonable, as the problem easily solved in Python, but not in C/C++/Java. As for the return value, there are a few options: Capture the printed output of the Python program. Have the Python program write the desired output to a well-defined file, and just ignore all other output.
🌐
Codingdeeply
codingdeeply.com › home › call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
February 23, 2024 - One common approach is to use the ProcessBuilder class to call the Python interpreter and pass the script name as an argument. This method is simple but may not be suitable for complex scenarios.
🌐
Quora
quora.com › How-do-I-call-Python-script-from-Java
How to call Python script from Java - Quora
Answer (1 of 4): The old approach. [code]Process p = Runtime.getRuntime().exec("python yourapp.py"); [/code]You can read up on how to actually read the output here: http://www.devdaily.com/java/edu/pj/pj010016 There is also an Apache library (the Apache exec project) that can help you with thi...
🌐
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
🌐
my tiny TechBlog
norwied.wordpress.com › 2012 › 03 › 28 › call-python-script-from-java-app
call python script from Java app – my tiny TechBlog
June 1, 2018 - Basically we execute the python script by envoking python2.6 and provide the path to the script as parameter, as you would normally do it if you exec the script in a terminal/bash.
Top answer
1 of 3
2

The problem had multiple layers and solutions: 1. I didn't put .py file in jar build config 2. After putting it I always got an exception that it is null because of a typo in code 3. After trying many ways to run it this one worked Cannot run python script from java jar . The important thing is to check if you added py file to the build config and to run it in a proper way since python cannot runt files from the zip and compressed states.

2 of 3
0

Assuming the script is in the jar file, you can get an input stream from the resource, and use it as the input to a Process created from the python interpreter:

// Note: the path to the script here is relative to the current class
// and follows strict resource name rules, since this is in a jar file
InputStream script = getClass().getResourceAsStream("visualize3D.py");

// The following creates a process to run python3.
// This assumes python3 is on the system path. Provide the full
// path to the python3 interpreter (e.g. /usr/bin/python3) if it's
// not on the path.

// The - option to python3 instructs it to execute a script provided
// as standard input.

Process process = new ProcessBuilder("python3", "-")
    .start() ;
OutputStream out = process.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while((read = script.read(buffer)) != -1) {
    pos.write(buffer, 0, read);
}
script.close();

For details on getting the correct path for the script, see How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?

🌐
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 ​
🌐
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.
🌐
Quora
quora.com › How-can-I-run-Python-code-in-Java-code-and-vice-versa
How to run Python code in Java code, and vice versa - Quora
Answer (1 of 3): Yes, Python code to run in Java Platform. Three-way to possible code intercept both languages 1. Runtime approach – Developer can run the Python program using the “exec” method in the Runtime class. Examole [code]Process p = Runtime.getRuntime().exec("python http://test1.py ...
🌐
GitHub
github.com › devlpr › javathon
GitHub - devlpr/javathon: How to run python scripts in Java · GitHub
How to run python scripts in Java. Contribute to devlpr/javathon development by creating an account on GitHub.
Author   devlpr