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. Answer from DragonLord999 on edureka.co
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.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 725750 โ€บ languages โ€บ Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
If you're going to use Runtime.exec() or one of the other external program execution resources, then you should actually use the absolute program path. That is "/usr/bin/python", not just "python". Don't depend on the JVM's shell path. You may also need to intercept the stdio paths for the python interpreter. If you just want to run a preset gnuradio from Java, that's probably it.
Discussions

python - Running a .py file from Java - Stack Overflow
I am trying to execute a .py file from java code. I move the .py file in the default dir of my java project and I call it using the following code: String cmd = "python/"; String py = "fil... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Call and receive output from Python script in Java? - Stack Overflow
Or, even though it would be very ... read the file in Java. Note: the actual communication between Java and Python is not a requirement of the problem I am trying to solve. This is, however, the only way I can think of to easily perform what needs to be done. ... I tested the previous answer of John Huang, published here git hub project jpserve It is the best solution because it links a java client to a real Python application that can execute your scripts, ... 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
How do I call and run a Python script using a Java script?
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 - best also formatted as code block 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. 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/markdown editor: 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/learnjava
3
2
September 4, 2022
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - Throughout this tutorial, weโ€™ll ... file called hello.py: ... Assuming we have a working Python installation when we run our script, we should see the message printed: ... 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 ...
๐ŸŒ
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 ...
๐ŸŒ
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 - JEP is looking for the libjep.jnilib file on macOS and libjep.so file on Linux. Besides all, for the Linux system, it will be a different environment variable name: export LD_LIBRARY_PATH="<your_user_path>/myenv/lib/python3.8/site-packages/jep"$LD_LIBRARY_PATH ยท You set up the JEP library. Now you can execute Python directly from Java.
๐ŸŒ
Jython
jython.org
Home | Jython
import org.python.util.PythonInterpreter; public class JythonHelloWorld { public static void main(String[] args) { try(PythonInterpreter pyInterp = new PythonInterpreter()) { pyInterp.exec("print('Hello Python World!')"); } } } from java.lang import System # Java import print('Running on Java version: ' + System.getProperty('java.version')) print('Unix time from Java: ' + str(System.currentTimeMillis()))
Find elsewhere
๐ŸŒ
pytz
pythonhosted.org โ€บ javabridge โ€บ java2python.html
Calling Python from Java โ€” python-javabridge 1.0.12 documentation
import javabridge cpython = javabridge.JClassWrapper('org.cellprofiler.javabridge.CPython')() d = javabridge.JClassWrapper('java.util.Hashtable')() result = javabridge.JClassWrapper('java.util.ArrayList')() d.put("result", result) cpython.execute( 'import javabridge\n' 'x = { "foo":"bar"}\n' 'ref_id = javabridge.create_and_lock_jref(x)\n' 'javabridge.JWrapper(result).add(ref_id)', d, d) cpython.execute( 'import javabridge\n' 'ref_id = javabridge.to_string(javabridge.JWrapper(result).get(0))\n' 'assert javabridge.redeem_jref(ref_id)["foo"] == "bar"\n' 'javabridge.unlock_jref(ref_id)', d, d)
๐ŸŒ
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...
๐ŸŒ
The SW Developer
theswdeveloper.com โ€บ post โ€บ java-python-jep
How to execute Python code in Java - The SW Developer
September 10, 2021 - Inject a String argument which will be used by the Python code: Our Python script argument named user_name will get the value of our Java code name variable. ... That's it. It's as simple as that.
Top answer
1 of 10
81

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.

๐ŸŒ
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
In case if your project has requirement to execute Python code from Java, here are few code samples that I have collected from Internet. Make data easy with Helical Insight. Helical Insight is the worldโ€™s best open source business intelligence tool. ... Python code that is written in a file which ... 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 โ€‹
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 579195 โ€บ java โ€บ Running-Python-script-runtime-exec
Running a Python script via runtime.exec (Java in General forum at Coderanch)
When I tried starting several scripts concurrently (which will happen often on the actual system), instead of creating a log file in the "log_<script_id>.txt", it created and repeatedly wrote over "log_0.txt". Script.java: Something like that. This is Script_1. Remember, all 6 thousand scripts I have are very similar - they all run a separate python file.
๐ŸŒ
Py4j
py4j.org
Welcome to Py4J โ€” Py4J
This is the Java program that was executing at the same time (no code was generated and no tool was required to run these programs). The AdditionApplication app instance is the gateway.entry_point in the previous code snippet. Note that the Java program must be started before executing the Python ...
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ article โ€บ execute-python-in-java
Execute Python In Java
August 1, 2022 - import org.python.util.PythonInterpreter; public class Sample { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); System.out.println("Java runs python code using jython"); interpreter.execfile("src/main/java/testPython.py"); System.out.println("x: " + interpreter.get("x")); System.out.println("x: " + interpreter.get("y")); } } In the above code, we can see that the interpreter object will execute the file.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ jython โ€บ jython_java_application.htm
Jython - Java Application
import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, world from Java"); interp.execfile("hello.py"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye "); } }
๐ŸŒ
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 an instance of the ProcessBuilder class and pass python and script path as parameters. Create a process to run the ProcessBuilder using the start() method; this will execute the Python script.
๐ŸŒ
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 - You can execute the java program in eclipse by click on the green run button or compile and exec it in a terminal with: cd workspace/JavaPythonCall/src/org/norbert javac PythonCaller.java cd ../.. java org.norbert.PythonCaller