Yes, that can be done . Normally this will be done by creating a PythonInterpreter object and then calling the python class using that .

Consider the following example :

Java :

import org.python.core.PyInstance;  
import org.python.util.PythonInterpreter;  


public class InterpreterExample  
{  

   PythonInterpreter interpreter = null;  


   public InterpreterExample()  
   {  
      PythonInterpreter.initialize(System.getProperties(),  
                                   System.getProperties(), new String[0]);  

      this.interpreter = new PythonInterpreter();  
   }  

   void execfile( final String fileName )  
   {  
      this.interpreter.execfile(fileName);  
   }  

   PyInstance createClass( final String className, final String opts )  
   {  
      return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");  
   }  

   public static void main( String gargs[] )  
   {  
      InterpreterExample ie = new InterpreterExample();  

      ie.execfile("hello.py");  

      PyInstance hello = ie.createClass("Hello", "None");  

      hello.invoke("run");  
   }  
} 

Python :

class Hello:  
    __gui = None  

    def __init__(self, gui):  
        self.__gui = gui  

    def run(self):  
        print 'Hello world!'
Answer from The Dark Knight on Stack Overflow
🌐
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.
🌐
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.
Discussions

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 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
Calling Java from Python - Stack Overflow
What is the best way to call java from python? (jython and RPC are not an option for me). I've heard of JCC: http://pypi.python.org/pypi/JCC/1.9 a C++ code generator for calling Java from C++/Pytho... More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
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.

🌐
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)
""" 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.
🌐
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.
Find elsewhere
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.
🌐
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 - Example of how to set up a Python Path for Jep library in Java · Second — to set up JEP configurations (we should add Python libraries to operate and our project folders). Then, create a SharedInterpreter object. A SharedInterpreter directly will execute python code or python executive document: Example of how to set up the Jep configurations and to create a SharedInterpreter for Python execution · I have a python document with two simple functions to check JEP work.
🌐
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.
🌐
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   oroppas
🌐
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...
🌐
Coderanch
coderanch.com › t › 725750 › languages › Running-python-py-script-Java
Running python (.py) script from Java code (Jython/Python forum at Coderanch)
I don't know python at all, so now I'm probably in over my head. This is a GNURadio script. Rob - A feature of my program is that users can change the GNURadio script (.py) to suit their signal processing needs. My java program then calls a GNURadio script to import data via TCP.
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
Three ways to run Python programs from Java - Post.Byes
June 15, 2013 - import java.io.*; class test2{ public static void main(String a[]){ try{ String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n"; BufferedWriter out = new BufferedWriter(new FileWriter("test1.py")); out.write(prg); out.close(); int number1 = 10; int number2 = 32; ProcessBuilder pb = new ProcessBuilder("python","test1.py",""+number1,""+number2); Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); int ret = new Integer(in.readLine()).intValue(); System.out.println("value is : "+ret); }catch(Exception e){System.out.println(e);} } } I saved the above as "test2.java ". Then I typed the following; javac test2.java To execute it: java test2 Jython approach Java is supposed to be platform independent, and to call a native application (like python) isn't very platform independent.
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › integrating-java-with-python
Integrating Java with Python - GeeksforGeeks
July 23, 2025 - First, the Python program should be able to access the Java Virtual Machine (JVM) running the Java program. This requires an instance of the GatewayServer class available in the library py4j that makes this communication possible.
🌐
LinkedIn
linkedin.com › pulse › integrating-python-java-guide-developers-myexamcloud-7g5bc
Integrating Python and Java: A Guide for Developers
December 26, 2023 - JPype is a Python module that enables integration with Java code via Java Virtual Machine (JVM). It provides an easy-to-use interface to call Java functions and libraries from within a Python program.
🌐
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. Compile and run the Java code. Ensure that the Python code file is correctly referenced in the Java project. 2. Observe the integration in action as the Java application calls the Python code and receives the computed results.