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.

🌐
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.
🌐
Baeldung
baeldung.com › home › java › how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named syds ... As PythonIntepreter implements AutoCloseable, it’s good practice to use try-with-resources when working with this class · The PythonInterpreter class name does not imply that our Python code is interpreted. Python programs in Jython are run by the JVM and therefore compiled to Java bytecode before execution
🌐
Openfoo
openfoo.org › blog › jython_python_function.html
Calling Python functions from Java using Jython - Sören Bleikertz
If we want to call a function written in Python from Java, which takes as input a Java object and returns another object, we can realize it using the following snippet build on Jython.
Top answer
1 of 2
1

Yes, this way is fine, but you can not run python script in constructor method, if so, it will be dead recursive at your code. please see the following code. you run PythonScriptTest class, it will run python script first, then python script will invoke PythonScriptTest.SpawnPlayer() method.

java code:

package com.xxx.jython;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;

public class PythonScriptTest {

    public static void main(String[] args) {
        PythonScriptTest f = new PythonScriptTest();
        f.executePythonScript();
    }

    public PythonScriptTest(){
    }

    public void executePythonScript() {
            PythonInterpreter interpreter = new PythonInterpreter();
            interpreter.execfile("/home/XXX/XXX/util.py");
            PyFunction pyFuntion = (PyFunction) interpreter.get("InGameCommand", PyFunction.class);

            pyFuntion.__call__();
    }

    public void SpawnPlayer() {
            System.out.println("Run SpawnPlayer method ##################");
    }
}

Python scripts, named util.py:

import sys.path as path
# the following path is eclipse output class dir
# does not contain java class package path.
path.append("/home/XXX/XXX/Test/bin")
from com.xxx.jython import PythonScriptTest

def add(a, b):  
    return a + b  

def InGameCommand():
    myJava = PythonScriptTest()
    myJava.SpawnPlayer()
2 of 2
1

need to jython.jar

  1. execute python code in java.

    import org.python.util.PythonInterpreter;  
    public class PythonScript{  
        public static void main(String args[]){  
            PythonInterpreter interpreter = new PythonInterpreter();  
            interpreter.exec("days=('One','Two','Three','Four'); ");  
            interpreter.exec("print days[1];");    
        }
    }  
    
  2. invoke python script method in java.

    python script file, named test.py

    def add(a, b):  
        return a + b  
    

    java code:

    import org.python.core.PyFunction;  
    import org.python.core.PyInteger;  
    import org.python.core.PyObject;  
    import org.python.util.PythonInterpreter;  
    
    public class PythonScript {  
        public static void main(String args[]) {  
    
            PythonInterpreter interpreter = new PythonInterpreter();  
            interpreter.execfile("/home/XXX/XXX/test.py");  
            PyFunction pyFuntion = (PyFunction)interpreter.get("add",PyFunction.class);  
    
            int a = 10, b = 20 ;  
            PyObject pyobj = pyFuntion.__call__(new PyInteger(a), new PyInteger(b));  
            System.out.println("result = " + pyobj.toString());  
       }
    }  
    
  3. run python script in java

    python script file, named test.py:

    number=[1,10,4,30,7,8,40]  
    print number  
    number.sort()  
    print number  
    

    java code:

    import org.python.util.PythonInterpreter;
    
    public class FirstJavaScript {
    
        public static void main(String args[]) {
             PythonInterpreter interpreter = new PythonInterpreter();
             interpreter.execfile("/home/XXX/XXX/test.py");
        }
    }
    
🌐
Medium
medium.com › @KosteRico › jython-run-python-code-inside-java-de4d12f227ae
The Beginner’s Guide To Jython: run Python code inside Java | by Konstantin Parakhin | Medium
November 30, 2021 - <dependency> <groupId>org.python</groupId> <artifactId>jython-slim</artifactId> <version>2.7.2</version> </dependency> First of all, we need to create PythonInterpreter object: ... We may run each type of code.
🌐
Robert Peng's Blog
mr-dai.github.io › embedding-jython
Embedding Python in Java using Jython - Robert Peng's Blog
September 10, 2018 - Groovy here actually wrap the given script in a newly created Java class (which extends Script), and so we can use this class to create new Script instances, and reuse the same compiled Groovy code. We can implement the same technique in Jython – actually the Jython Book has also mentioned this kind of usage, which named Object Factory. You can choose to compile your Python code in a Python class, but we will just use it as a Python function here, which suffices in our scenario:
Find elsewhere
🌐
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.
🌐
breekmd
breekmd.wordpress.com › 2015 › 03 › 19 › call-python-from-java
Call Python from Java - breekmd - WordPress.com
March 19, 2015 - package com.wordpress.breekmd.java; import org.python.util.PythonInterpreter; public class JavaMain { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); try { interpreter.execfile("D:/Projects workspace/JavaPythonMix/src/com/wordpress/breekmd/java/PythonMain.py"); } catch (Exception e) { e.printStackTrace(); } } } ... Hello. Test Succeeded! Ain’t that simple? Now let’s try and call only a specific method from the .py file, not the entire file. We’re going to modify the Java code a little and create a new .py file and add it to the /Jython/Lib folder.
🌐
Jython
jython.org › jython-old-sites › archive › 22 › userguide.html
Jython User Guide
There are two options for embedding Jython in a Java application. You can make a real Java class out of a Python class, and then call it from your Java code, as previously described, or you can use the PythonInterpreter object
🌐
Python Software Foundation
wiki.python.org › jython › LearningJython
Jython Course Outline - Python Wiki
In order to call Java code from Jython do the following: Import the Java module. Use the Java module to create an instance/object. Call functions and objects in it.
🌐
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 ...
🌐
YouTube
youtube.com › ck tv
Run Python in Java using Jython - YouTube
This video is a demonstration of how to run Python code using Java. All the steps are clearly defined.
Published   February 11, 2022
Views   17K
🌐
Coderanch
coderanch.com › t › 153 › languages › Calling-python-function-java
Calling python function from java (Jython/Python forum at Coderanch)
Hi , I have a java file as below : public class myClass { public int myMethod() { PythonInterpreter interpreter = new PythonInterpreter(); //Code to write } } I have one python file as below : import string; from jythonlib.tl1pc.utils import * class myPythonClass: def abc(self): print "calling abc" tmpb = {} tmpb = { 'status' : 'SUCCESS' } return tmpb Now the problem is i want to call "abc" function of my python file from "myMethod" method of my java file.
Top answer
1 of 2
7

You can use PyObject.__call__(Object... args) to invoke any callable Python object. You can get the PyFunction representing your function from the java side the same way you example is getting the python employee class.

Alternativeley, you can hide this behind a single method interface on the java side by calling __tojava__(Interface.class) on the function you retrieved from the Python interpreter. Detailed example (actually tested!): python file:

def tmp():
    return "some text"

java:

public interface I{
    public String tmp();
}

public static void main(String[] args) {
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("from test import tmp");
    PyObject tmpFunction = interpreter.get("tmp");
    System.err.println(tmpFunction.getClass());
    I i = (I) x.__tojava__(I.class);
    System.err.println(i.tmp());

}

output:

class org.python.core.PyFunction
some text
2 of 2
2

Importing only a method isn't possible because in Java, methods (or functions) aren't first-class objects, i.e. there's no way to refer to a method without first referring to some class (or interface). Even static methods are enclosed in a class and you refer to them via the class object.

However, you can get fairly close with the solution in introduced in Jython 2.5.2: Jython functions work directly as implementations of single abstract method Java interfaces (see http://www.zyasoft.com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/). So you can define an interface in Java - it's essential that it contains exactly one method definition:

interface MyInterface {
    int multiply(int x, int y);
}

Plus something like this in Jython:

myFunction = lambda x, y : x * y

and use that as a MyInterface in Java. You still have to use some sort of factory pattern, as described in the article you linked to, to get the Jython function to Java, but something like this works (probably contains errors, but the idea is):

PyObject myFunction = interpreter.get("myFunction"); 
MyInterface myInterface = (MyInterface)myFunction.__tojava__(MyInterface.class);
int x = myInterface.multiply(2, 3); // Should return 6.
🌐
Codingdeeply
codingdeeply.com › home › call python script from java: seamless integration guide
Call Python Script from Java: Seamless Integration Guide
February 23, 2024 - Once you define your Python function, you can call it from your Java code using the Jython library.