Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python from within Java [duplicate]

Possible Duplicate:
Java Python Integration

I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this.

I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this?

If not, what would be the best method to interface between Java and Python, such that (ideally) I can call a method in Python and have the result returned to Java?

like image 957
Liam Avatar asked Jul 22 '09 12:07

Liam


People also ask

Can you use both Java and Python together?

The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.

Can I call a Python file from Java?

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.

How do you call a Python script from Java?

First, we begin by setting up a ScriptContext which contains a StringWriter. This will be used to store the output from the script we want to invoke. We then use the getEngineByName method of the ScriptEngineManager class to look up and create a ScriptEngine for a given short name.

What is difference between Python and Jython?

Difference between Python and JythonReference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation. Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it.


2 Answers

I would write a Python module to handle the text and language processing, and then build a small bridge in jython that your java program can interact with. The jython bridge will be a very simple one, that's really only responsible for forwarding calls to the python module, and return the answer from the python module to the java module. Jython is really easy to use, and setup shouldn't take you more than 15 minutes.

Best of luck!

like image 44
Mia Clarke Avatar answered Sep 25 '22 02:09

Mia Clarke


I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this?

Yes, you are wrong. You can either call a command line interpreter to run python code using Jyton or use python code from Java. In the past there was also a python-to-Java compiler, but it got discontinued with Jython 2.2

like image 121
Michael Borgwardt Avatar answered Sep 21 '22 02:09

Michael Borgwardt