3

Instead of using Jython, is there any way to call a Java program from Python?

This Java program contains some function and I need to give an input file to Java code and it returns two values which I will be using in Python. So the Python program passes a filename to the Java code and the Java code will return two values for each line in that file.

For example I have the following file containg data like given below:

22      16050408        2       2184    T:0.938645      C:0.0613553
22      16050612        2       2184    C:0.915751      G:0.0842491
22      16050678        2       2184    C:0.94826       T:0.0517399
22      16050984        2       2184    C:0.997711      G:0.00228938
22      16051107        2       2184    C:0.94185       A:0.0581502

I need give a file to the Java program and it will return two values for each line of that file. So the number of lines in the file containg the above data, input to java code will be the same. I need to replace the column two with two columns.. i.e. the values returned by Java.

Please kindly help

4

2 回答 2

2

您始终可以将 java 程序作为命令行工具来调用——那么程序是什么语言并不重要。为此,我建议使用subprocess模块。您甚至可以在不使用文件系统上的任何临时文件的情况下将输入/输出通过管道传输到您的 python 程序。以下示例运行 java 应用程序并获取其输出:

prog = subprocess.Popen(["/usr/bin/java", "TestClass"], stdout=subprocess.PIPE)
print prog.stdout.read() 

另一种选择,虽然涉及更多的是使用py4j

Py4J 使在 Python 解释器中运行的 Python 程序能够动态访问 Java 虚拟机中的 Java 对象。调用方法就像 Java 对象驻留在 Python 解释器中一样,并且可以通过标准 Python 集合方法访问 Java 集合。Py4J 还使 Java 程序能够回调 Python 对象。Py4J 在 BSD 许可下分发。

我认为这听起来确实像你正在做的事情..

Py4J 的优势在于它是一种更便携的解决方案,它使用套接字在 java 和 python 程序之间进行通信——您不是在 python 环境中运行 JVM,而是与运行 py4j 网关的现有 JVM 实例“通信”。

于 2012-10-30T12:17:24.477 回答
1

你可以试试JPype

这是文档中有关使用的引用:

from jpype import * 
startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") 
java.lang.System.out.println("hello world") 
shutdownJVM() 

这将启动一个专用的 JVM,您可以在其中运行您的 Java 代码,从 Python 透明地调用它。

尽管在您的情况下,我相信您确实可以将例程作为子进程运行,并且如果您将来需要这样做,还具有从 Java 轻松切换到其他任何东西的优势。

于 2012-10-30T12:17:37.187 回答