You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J

Answer from Barthelemy on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - Once we have an endpoint we can access, we can use any one of several Java HTTP libraries to invoke our Python web service/application implementation. In this tutorial, weโ€™ve learned about some of the most popular technologies for calling Python code from Java.
Discussions

Calling Python in Java? - Stack Overflow
I am wondering if it is possible to call Python functions from Java code using Jython, or is it only for calling Java code from Python? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can we call a python method from java? - Stack Overflow
I know jython allows us to call a java method from any java's classfile as if they were written for python, but is the reverse possible ??? I already have so many algorithms that written in python... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
Calling python function from java
In java, I'm trying to build context for python function and call the python function as java function. When I check the members of evaluated context, all I see is close. What am I doing wrong ... More on github.com
๐ŸŒ github.com
4
May 7, 2019
Calling Python Functions from Java Using Jython - Ask a Question - 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.testmuai.com
๐ŸŒ community.testmuai.com
0
January 14, 2025
People also ask

How can I call Python scripts from Java?
Once the environment is set up, you can call Python scripts from your Java application. We will show you how to invoke Python scripts and pass data between Java and Python. Various methods and techniques are available for calling Python code from Java, and we will provide detailed examples and code snippets to help you understand the process.
๐ŸŒ
codingdeeply.com
codingdeeply.com โ€บ home โ€บ call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
Can I integrate Python functions with Java?
Yes, in addition to calling entire Python scripts, you can also integrate specific Python functions with your Java application. We will guide you through the process of invoking Python functions from Java, passing arguments, and retrieving results. This allows you to leverage the functionality of Python libraries within your Java application.
๐ŸŒ
codingdeeply.com
codingdeeply.com โ€บ home โ€บ call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
What is the benefit of integrating Python with Java?
By combining Python and Java, you can leverage the extensive libraries and frameworks available in Python while taking advantage of Java's robustness and scalability. It also allows you to reuse existing Python code without rewriting it in Java, saving development time and effort.
๐ŸŒ
codingdeeply.com
codingdeeply.com โ€บ home โ€บ call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
๐ŸŒ
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) ... Enter search terms or a module, class or function name.
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.

๐ŸŒ
GitHub
github.com โ€บ oracle โ€บ graalpython โ€บ issues โ€บ 81
Calling python function from java ยท Issue #81 ยท oracle/graalpython
May 7, 2019 - import java.util.*; import java.io.*; import org.graalvm.polyglot.*; import org.graalvm.polyglot.proxy.*; public class main { public static void main(String[] args) { try { OutputStream myOut = new BufferedOutputStream(new FileOutputStream("demo_polyglot.log")); Context context = Context.newBuilder("python") .out(myOut) .allowIO(true) .allowPolyglotAccess(PolyglotAccess.ALL) .build(); String dir = "."; String name = "demo_polyglot.py"; File file = new File(dir, name); assert name.endsWith(".py") : "make sure it's python file"; String language = Source.findLanguage(file); Source source = Source
Author ย  oracle
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 - Four lines of code, and we have a python3.9 Interpreter in Java! Now you will see how to run the Python functions from the document youโ€™ve already seen.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 537787 โ€บ languages โ€บ call-Python-method-form-Java
How to call a Python method form Java class (Jython/Python forum at Coderanch)
May 13, 2011 - """ def __init__(self, gui): self.gui = gui self.numbers = None self.vendor = None self.raNumber = None self.comPort = None self.logFile = None self.thread = None self.results = None self.testSuite = None self.retryEvent = None def run(self,logFile,comPort,numbers,vendor,raNumber,testSuite,SerialErrorEvent,ProcessingErrorEvent): """ """ self.logFile = logFile self.comPort = comPort self.serialNumbers = serialNumbers self.vendor = vendor self.raNumber = raNumber self.SerialErrorEvent = SerialErrorEvent self.ProcessingErrorEvent = ProcessingErrorEvent try: ................ ........... and my java class is as below: PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]); PythonInterpreter interp = new PythonInterpreter(); System.out.println(); interp.execfile("E:\\processing.py"); Now want to call the method run from java class.
๐ŸŒ
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.
๐ŸŒ
Codingdeeply
codingdeeply.com โ€บ home โ€บ call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
February 23, 2024 - You will learn to call Python script from Java and execute it within your Java application. This integration allows you to leverage the strengths of both programming languages, opening up new possibilities for your development projects. We have you covered whether you need to invoke Python scripts, execute Python code, or use Python functions ...
๐ŸŒ
TestMu AI Community
community.testmuai.com โ€บ ask a question
Calling Python Functions from Java Using Jython - Ask a Question - 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.
๐ŸŒ
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...
๐ŸŒ
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. Now let us understand the Jpype with a working example. Below example demonstrate usage of Jpype module. from jpype import * startJVM(getDefaultJVMPath(), "-ea") java.lang.System.out.println("Calling Java Print from Python using Jpype!") shutdownJVM()
๐ŸŒ
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.

๐ŸŒ
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:
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ examples โ€บ call-java-using-python
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.
๐ŸŒ
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(); } }
๐ŸŒ
Blogger
automation-home.blogspot.com โ€บ 2015 โ€บ 12 โ€บ call-python-script-functions-from-java.html
Java - Call python script functions from java code | Automation Home
December 9, 2015 - Download "jython-standalone-<<version>>.jar" from http://www.jython.org/downloads.html Now set the java build path for downloaded jar file. Now execute the java code again. To avoid error message "console: Failed to install" displayed in console. Add the "VM agruments" as "-Dpython.console.encoding=UTF-8", and re-execute the program again. Note: For executing the python script function from java code using above procedure, doesn't require python software installed on your machine.