Faram
Faram

Reputation: 555

Call Python 3.x functions in Java

I want to call Python functions in Java. I know there is Jython, which comes with the PythonInterpreter for Java, but sadly it only supports Python 2.7.

For a better explanation of what I want to do. Let's say I have the following Python code in a given file:

@staticmethod
def my_first_function():
   print("Hi!")

@staticmethod
def my_second_function():
   print("Hi again!")

I want to be able to EXPLICITLY call functions like this in Java now:

PythonToJava pythonToJava = new PythonToJava("my/python/script/path");
pythonToJava.my_second_function(); 
pythonToJava.my_first_function();

How can I use/call a Python module/script/class/etc. in Java?

Upvotes: 5

Views: 3717

Answers (1)

GiulioP
GiulioP

Reputation: 126

How about using the Runtime.exec() method? Just do Process process = Runtime.getRuntime().exec("python script.py arg1 arg2"). Runtime is a class from the java.lang package, so you don't need to do any fancy import.

More info here.

EDIT

Ok, not too easy to manage if you have lots of functions. On the other hand if you don't mind a bunch of wrapper files just do a bit of code to build one automatically for each function.

Check out this little piece of Python code. Just replace foo with whatever your huge module is called, and you're good to go.

from inspect import getmembers, isfunction
import foo

f_list=[o[0] for o in getmembers(foo) if isfunction(o[1])]
for x in f_list:
    print("Build "+str(x))
    with open("helper_"+str(x)+".py","wt") as f:
        f.write("""import foo
import sys

arg_list=sys.argv[1::]
print(foo.{x}(*arg_list))""".format(x=x))

Upvotes: 4

Related Questions