Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Calling python module from Java

I want to call a function from a python module from Java using "PythonInterpreter" and here's my Java code

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");

PyObject someFunc = interpreter.get("helloworld.getName");

PyObject result = someFunc.__call__();

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

and the Python code (helloworld.py) is below:

    from faker import Factory
    fake = Factory.create()

    def getName():
       name = fake.name()
       return name  

The problem I'm facing is while I'm calling interpreter.get when it returns a null PyObject.

Any idea what's going wrong? The python code runs fine from IDLE

EDIT

I just did a bit of change in the code as below

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");


PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");  

PyObject result = wrapper.invoke("getName()");

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

and I introduced a class in my python module

from faker import Factory

class helloworld:

def init(self):
    fake = Factory.create()

def getName():
    name = fake.name()
    return name 

Now am getting the error below

Exception in thread "main" Traceback (innermost last):
  File "<string>", line 1, in ?
TypeError: call of non-function (java package 'helloworld')

Answer*

Draft saved
Draft discarded

Required fields are marked with *

Cancel
1
  • in your solution how could you pass arguments to get_name(self, something)? Commented Nov 15, 2021 at 17:10

default