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

Answer from Voo on Stack Overflow
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.

🌐
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 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 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.
Discussions

Best way to combine Python and Java?
I've used JPype for a while. It also starts a JVM from python. Once set up, interoperating with Java is transparent. You can start the JVM in such a way that it can be debugged directly using remote debugging tools. More on reddit.com
🌐 r/java
82
60
October 29, 2022
What is the best way to run Java code from Python?
Java and Python are two different worlds apart. The only way to integrate them is via inter-process communication. That's what py4j does, it uses sockets and an internal protocol. Jython is a different story, it runs Python code on the JVM, so your python code will be the guest, and the Java application will be the host. You can do fine with REST, or even by invoking a Java application as a subprocess and collecting the outputstream. More on reddit.com
🌐 r/Python
4
1
June 4, 2018
Calling Python Functions from Java Using Jython - TestMu AI Community
Is it possible to call Python functions from Java code using Jython, or is Jython only useful for calling Java code from Python? I’m specifically looking to call Python from Java. More on community.testmu.ai
🌐 community.testmu.ai
0
January 14, 2025
How can I call Python from Java?
How about using jni to write a c++ module that can run the python interpreter? Here is an api for using python interpreter from QML/JS: https://github.com/thp/pyotherside/blob/master/src/qpython.h . you can create a similar jni module for your java code: https://en.m.wikipedia.org/wiki/Java_Native_Interface More on reddit.com
🌐 r/learnprogramming
2
2
June 17, 2020
🌐
pytz
pythonhosted.org › javabridge › java2python.html
Calling Python from Java — python-javabridge 1.0.12 documentation
class MyClass { static final CPython ... result; } } ... execute is a synonym for exec which is a Python keyword. Use execute in place of exec to call Python from a javabridge CWrapper for CPython....
🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
>>> from py4j.java_gateway import JavaGateway >>> gateway = JavaGateway() # connect to the JVM >>> random = gateway.jvm.java.util.Random() # create a java.util.Random instance >>> number1 = random.nextInt(10) # call the Random.nextInt method >>> number2 = random.nextInt(10) >>> print(number1, number2) (2, 7) >>> addition_app = gateway.entry_point # get the AdditionApplication instance >>> value = addition_app.addition(number1, number2) # call the addition method >>> print(value) 9 · 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 code above.
🌐
Reddit
reddit.com › r/java › best way to combine python and java?
r/java on Reddit: Best way to combine Python and Java?
October 29, 2022 -

My project uses some packages that are available only in Python and heavily rely on C libraries. The project also greatly benefits from Java libraries and the JVM. What's the optimal way to call Python functions from Java?

I tried:

  1. Small web-services: overhead to serialize data, start and stop the services. Also debugging is harder and implementing each new function is now double the effort.

  2. Jpy: a library that runs an interpreter in the JVM. Spare the service start/stop, but: isn't really feasible for more than a single-liner, data translation between Java and Python is cumbersome, and I also encountered runtime segmentation fault errors.

Any other options?

The project is in the machine-learning domain, so involves exchanging large numeric arrays and text. In some cases the execution switches back and forth between the platforms.

🌐
Coderanch
coderanch.com › t › 725750 › languages › Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
My java program then calls a GNURadio script to import data via TCP. Users shouldn't need to edit the java, so embedding python inside the java wouldn't work well for me. Kristina - It would have been far wiser to start the entire project in python. Alas, I chose java early on (because it's what I knew), and now I'm too far along to change. The basic workflow is that a user can start the python from within the java GUI.
Find elsewhere
🌐
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 - So what are we going to do? What kind of solutions do we apply to this task? One of the working solutions is to run this service in docker. Or we can find another, more effective production-friendly solution: to execute python code directly from Java code via the Jep library (Java Embedded Python).
🌐
AskPython
askpython.com › home › how to call java using python with jpype and pyjnius
Calling Java using Python | #1 guide to Jpype
November 8, 2023 - #1 Guide to learn how to use Jpype1 and Pyjnius to Call Java using Python by making use of JPype1 and Pyjnius in Python.
🌐
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. ^.^

🌐
Jython
jython.org
Home | Jython
The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products. 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()))
🌐
GeeksforGeeks
geeksforgeeks.org › java › integrating-java-with-python
Integrating Java with Python - GeeksforGeeks
July 23, 2025 - To invoke an existing Java application in Python, we need a bridge between Python and Java. Packages like Py4j, Pyjnius, Jpype, javabridge, and JCC help invoke Java programs from Python.
🌐
Readthedocs
jpy.readthedocs.io › en › latest › intro.html
Introduction — jpy 0.9.0 documentation
Java programs with jpy.jar on the classpath can import Python modules, access module attributes such as class types and variables, and call any callable objects such as module-level functions, class constructors, as well as static and instance class methods. Instantiate Python objects from Java classes and call their public methods and fields:
🌐
Dwgeek
dwgeek.com › home › execute java from python, syntax and examples
Execute Java from Python, Syntax and Examples - DWgeek.com
May 24, 2019 - You can use pip to install Jpype in your Python distribution. ... If you are using Anaconda distribution, then this module is already included in the package. You just have to import required methods from it and start using it.
🌐
Liacs
rsewiki.liacs.nl › calling_java_from_python
Calling Java from Python [LIACS Wiki]
April 1, 2021 - Good: py4j can be a good candidate to allows python interaction with a long-running java program/server. py4j do not start the JVM by itself. The JVM needs to be started prior to the execution of the python code and creates an application gateway. ... import py4j.GatewayServer; public class GatewayApplication { public int called_from_python(int first, int second) { return first + second; } public static void main(String[] args) { GatewayApplication app = new GatewayApplication(); // app is now the gateway.entry_point GatewayServer server = new GatewayServer(app); server.start(); } }
🌐
Manmustbecool
manmustbecool.github.io › MyWiki › Wiki › Python › python_java.html
Call Java from Python
from py4j.java_gateway import JavaGateway gateway = JavaGateway() # connect to the JVM random = gateway.jvm.java.util.Random() # create a java.util.Random instance number1 = random.nextInt(10) # call the Random.nextInt method print(number1) AdditionApplication addition_app = new gateway.jvm.AdditionApplication() # get the AdditionApplication instance value = addition_app.addition(4, 5)) # call the addition method print(value)
🌐
Sails Software Inc
sailssoftware.com › how-to-call-python-code-from-java-and-vice-versa
How to Call Python Code from Java and Vice Versa - Sails Software Inc
July 18, 2023 - 1. Create a new Java project in your preferred IDE. 2. Configure the project to include the necessary dependencies to call Python code.
🌐
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...
🌐
Jython
jython.org › jython-old-sites › archive › 21 › docs › usejava.html
Accessing Java from Jython
One of the goals of Jython is to make it as simple as possible to use existing Java libraries from Python. Example · The following example of an interactive session with Jython shows how a user could create an instance of the Java random number class (found in java.util.Random) and then interact ...
🌐
TestMu AI Community
community.testmu.ai › ask a question
Calling Python Functions from Java Using Jython - TestMu AI Community
January 14, 2025 - Is it possible to call Python functions from Java code using Jython, or is Jython only useful for calling Java code from Python? I’m specifically looking to call Python from Java.