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
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - Learn the most common ways of calling Python code from Java.
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.
Discussions

Executing Java programs through Python - Stack Overflow
Of course, Jython allows you to use Java classes from within Python. More on stackoverflow.com
🌐 stackoverflow.com
November 8, 2011
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
Calling Java from Python - Stack Overflow
Through my own experience trying ... within java code in python, I was unable to find a straightforward methodology. My solution to my problem was by running this java code as BeanShell scripts by calling the BeanShell interpreter as a shell command from within my python code ... More on stackoverflow.com
🌐 stackoverflow.com
Call and receive output from Python script in Java? - Stack Overflow
What's the easiest way to execute a Python script from Java, and receive the output of that script? I've looked for different libraries like Jepp or Jython, but most appear out of date. Another pro... 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)
Once the virtual environment is ... base of the Python project, run the virtual environment's activate command, then run your program with the "python <program.py>" command....
🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
Here is a brief example of what you can do with Py4J. The following Python program creates a java.util.Random instance from a JVM and calls some of its methods.
🌐
Python Software Foundation
wiki.python.org › jython › LearningJython
Jython Course Outline - Python Wiki
Include a class in your script that creates an instance of java.util.Vector. Make the script both "run-able" and "import-able". From the Jython interpreter, import the script and create an instance of the class. From the command line, use jython to run the script.
Find elsewhere
🌐
Dwgeek
dwgeek.com › home › execute java from python, syntax and examples
Execute Java from Python, Syntax and Examples - DWgeek.com
May 24, 2019 - Execute Java from Python, Syntax and Examples, Python Jpype Module, Interact with Java from Python, Access java libraries from Python script
🌐
GitHub
github.com › laffra › pava
GitHub - laffra/pava: Run Java in Python · GitHub
Of course, the Python VM needs to be instructed where to find the Java class files. This is done by informing pava of the classpath to use: import pava pava.set_classpath(['...the location of the Java classfiles...']) Pava execution happens in two phases. In the first phase, before anything really runs, the Java classpath is processed and classfiles are transpiled.
Author   laffra
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.

🌐
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()))
🌐
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)
🌐
The SW Developer
theswdeveloper.com › post › java-python-jep
How to execute Python code in Java - The SW Developer
September 10, 2021 - The more common use case for Jep is running an entire Python script with a single Java command.
🌐
Reddit
reddit.com › r/python › what is the best way to run java code from python?
r/Python on Reddit: What is the best way to run Java code from Python?
June 4, 2018 -

Context: I'm working on something that requires me to use some API, which it so happens that is more extensive in its Java version (yes, even more extensive than it's REST api counterpart). My application is written with python and it would be of really useful if I could lay my hand on one particular endpoint available for the java api.

Could I access the java code from inside python? Or is the only way to make a separate java web service? I've been looking at Jython and Py4J, but I haven't seen any documentation on how to use third party libraries. Any help or advice on this is highly appreciated. ^.^

🌐
Stack Overflow
stackoverflow.com › questions › 60942476 › running-java-command-in-python
running java command in python - Stack Overflow
As an aside, you should be using subprocess.run instead, subprocess.call is an older API that is kept around for compatibility purposes ... Hackathons and free pizza: All about Stack Overflow’s new Student Ambassador... ... Reviewer overboard! Or a request to improve the onboarding guidance for new... 4189 What are the differences between a HashMap and a Hashtable in Java? 7520 Is Java "pass-by-reference" or "pass-by-value"? 5784 How do I execute a program or call a system command?
Top answer
1 of 12
116

Jython: Python for the Java Platform - http://www.jython.org/index.html

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

As of 2021, Jython does not support Python 3.x

2 of 12
77

I think there are some important things to consider first with how strong you wish to have the linking between Java and Python.

Firstly Do you only want to call functions or do you actually want Python code to change the data in your java objects? This is very important. If you only want to call some Python code with or without arguments, then that is not very difficult. If your arguments are primitives it makes it even more easy. However, if you want to have Java class implement member functions in Python, which change the data of the Java object, then this is not so easy or straight forward.

Secondly are we talking CPython, or will Jython do? I would say CPython is where its at! I would advocate this is why Python is so kool! Having such high abstractions however access to C or C++ when needed. Imagine if you could have that in Java. This question is not even worth asking if Jython is ok because then it is easy anyway.

So I have played with the following methods, and listed them from easy to difficult:

Java to Jython

Advantages: Trivially easy. Have actual references to Java objects

Disadvantages: No CPython, Extremely Slow!

Jython from Java is so easy, and if this is really enough then great. However it is very slow and no CPython! Is life worth living without CPython? I don't think so! You can easily have Python code implementing your member functions for you Java objects.

Java to Jython to CPython via Pyro

Pyro is the remote object module for Python. You have some object on a CPython interpreter, and you can send it objects which are transferred via serialization and it can also return objects via this method. Note that if you send a serialized Python object from Jython and then call some functions which change the data in its members, then you will not see those changes in Java. You just need to remember to send back the data which you want from Pyro. This, I believe, is the easiest way to get to CPython! You do not need any JNI or JNA or SWIG or .... You don't need to know any C, or C++. Kool huh?

Advantages:

  • Access to CPython
  • Not as difficult as following methods

Disadvantages:

  • Cannot change the member data of Java objects directly from Python
  • Is somewhat indirect (Jython is middle man)

Java to C/C++ via JNI/JNA/SWIG to Python via Embedded interpreter (maybe using BOOST Libraries?)

OMG this method is not for the faint of heart. And I can tell you it has taken me very long to achieve this in with a decent method. Main reason you would want to do this is so that you can run CPython code which as full rein over you java object. There are major things to consider before deciding to try and breed Java (which is like a chimp) with Python (which is like a horse). Firstly if you crash the interpreter, that's lights out for you program! And don't get me started on concurrency issues! In addition, there is a lot of boiler, I believe I have found the best configuration to minimize this boiler but it is still a lot! So how to go about this: Consider that C++ is your middle man, your objects are actually C++ objects! Good that you know that now. Just write your object as if your program is in C++ and not Java, with the data you want to access from both worlds. Then you can use the wrapper generator called SWIG to make this accessible to java and compile a dll which you call (System.load(dllNameHere)) in Java. Get this working first, then move on to the hard part! To get to Python you need to embed an interpreter. Firstly I suggest doing some hello interpreter programs or this tutorial Embedding Python in C/C. Once you have that working, its time to make the horse and the monkey dance! You can send you C++ object to Python via [boost][3] . I know I have not given you the fish, merely told you where to find the fish. Some pointers to note for this when compiling.

When you compile boost you will need to compile a shared library. And you need to include and link to the stuff you need from jdk, ie jawt.lib, jvm.lib, (you will also need the client jvm.dll in your path when launching the application) As well as the python27.lib or whatever and the boost_python-vc100-mt-1_55.lib. Then include Python/include, jdk/include, boost and only use shared libraries (dlls) otherwise boost has a teary. And yeah full on I know. There are so many ways in which this can go sour. So make sure you get each thing done block by block. Then put them together.

🌐
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
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 "+n...