开发者

passing data between java and python

Apologies if my question is noob. I'm running Django 1.2 with pgsql 8.4 and I'm required to run a Java program after getting the inputs from the user, does some calculations and return the results back to the user.

May I know what is the best way to pass data between the Java and Python Django, such that the above scenario are taken care of? I heard of Jython, but according to the Django docs, 开发者_如何学Pythonit requires the extension jython-Django, but currently it doesn't support django 1.2.x. Should I pass the data using stdout?

thanks people for hearing me out.


If all you are doing is calling Java for some calculations, then subprocess is the easiest way, but I just wanted to throw another option out there.

JPype is a package that lets you run a JVM inside your Python program while calling the Java code as if it were Python (example).

That is, it's like Jython in that you call Java code directly and like subprocess in that you are actually running CPython. Consider JPype if for some reason the Java code is not easy to call from a shell script (aka, subprocess) or if a lot of two-way communication is necessary.


Use subprocess and run the Java program as a simple subprocess. It's very, very simple and reasonably fast.

If you need to do something more scalable, you should look at creating a glassfish server with your Java code so your Python can make web services requests to the Java. This is more scalable, but also more work.


You can also use Py4J for this task:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
gateway.jvm.java.lang.System.out.println('Hello World!')

You should first start the Java program, and then invoke Java method from Python.

py4j doesn't start jvm, it just connects to the already started Java process.


It might be what you wanted to avoid. but at the most simple way of things, using sockets / shared file with java will be the best solution. python socket can send information and revise it from java. On the other hand if that feel like a pain. if you use java and python at the same computer you can use a shared file, that java can read from and python can wright to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜