简体   繁体   English

使用python中的java库(java包的Python包装器)

[英]Use java library from python (Python wrapper for java library)

I have a java library in jar form which can be used to extract data from files(excel,xml etc). 我有一个jar形式的java库,可用于从文件中提取数据(excel,xml等)。 As its in java, it can be used only in java applications. 正如它在java中一样,它只能在java应用程序中使用。 But i need the same library to be used for python projects as well. 但是我需要同样的库来用于python项目。 I have tried py4j etc which takes the objects from jvm. 我试过py4j等从jvm获取对象。 But the library is not an executable and wont be 'run'. 但该库不是可执行文件,不会“运行”。 I have checked Jython but i need the library to be accessible from Python projects. 我已经检查过Jython,但我需要可以从Python项目访问该库。 I have thought about using automated java to python translators, but i would take that as the last resort. 我曾考虑过将自动java用于python翻译器,但我认为这是最后的选择。

Please suggest some way i can accomplish this. 请提出一些我可以做到这一点的方法。

You can make a one class java program with a thread never ending until you send from Python a notification to do so. 在从Python发送通知之前,您可以使用一个永不结束的线程创建一个类java程序。

This way the lib would be kept in memory and accessible from your Python program. 这样lib就可以保存在内存中,并可以从Python程序中访问。

This class could be like this (add your needed lib import/init) : 这个类可能是这样的(添加你需要的lib import / init):

public class TestPy {

    private Thread thread;

    public void die() {
        synchronized (thread) {
            thread.interrupt();
        }    
    }

    public TestPy() {
        thread = new Thread(){
            public void run() {
                try {
                    while (!Thread.interrupted()) {
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
        thread.start();    
    }

    public static void main(String[] args) {
        TestPy tp = new TestPy();
        GatewayServer server = new GatewayServer(tp);
        server.start();
    }
}

You would have to launch the java program, use the lib, and then use the die() method to kill the java program in Python : 你必须启动java程序,使用lib,然后使用die()方法杀死Python中的java程序:

gateway = JavaGateway()
do your stuff here using the lib
tp = gateway.entry_point
tp.die()

You can write a simple command line Java program which calls the library and saves the results in a format you can read in Python, then you can call the program from Python using os.system . 您可以编写一个简单的命令行Java程序,该程序调用库并以Python中可读取的格式保存结果,然后您可以使用os.system从Python调用该程序。

Another option is to find Python libraries with equivalent functionality to the Java library: you can read excel, xml and other files in Python, that's not a problem. 另一个选择是找到与Java库具有相同功能的Python库:您可以在Python中读取excel,xml和其他文件,这不是问题。

I haven't learned how to create new instances of java class in a jar file by java constructors, but accidentally found that it's very easy to use any java static methods to access java objects in py2j. 我还没有学习如何通过java构造函数在jar文件中创建java类的新实例,但是偶然发现使用任何java静态方法来访问py2j中的java对象非常容易。

step 1: download py4j zip file from https://pypi.python.org/pypi/py4j . 第1步:从https://pypi.python.org/pypi/py4j下载py4j zip文件。 "py4j0.10.0.jar" is in the zip file. “py4j0.10.0.jar”在zip文件中。

step 2: install py4j by 第2步:安装py4j

pip install 'D:\Downloads\py4j-0.10.0.zip'

step 3: add py4j0.10.0.jar as well as the_lib_you_use.jar (like owlapi-distribution-3.5.0.jar for the example below) to build path in your eclipse project 第3步:添加py4j0.10.0.jar以及the_lib_you_use.jar(如下例中的owlapi-distribution-3.5.0.jar)来构建eclipse项目中的路径

step 4: create AdditionApplication.java, and copy and paste the code of AdditionApplication.java at https://www.py4j.org/ , and run Java application AdditionApplication.java 步骤4:创建AdditionApplication.java,并在https://www.py4j.org/上复制并粘贴AdditionApplication.java的代码,然后运行Java应用程序AdditionApplication.java

step 5: after running AdditoinApplication.java, test the example code in a python file: 步骤5:运行AdditoinApplication.java后,在python文件中测试示例代码:

if __name__ == '__main__':
    pass

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                   # connect to the JVM

random = gateway.jvm.java.util.Random()   # create a java.util.Random instance
number1 = random.nextInt(10)              # call the Random.nextInt method
number2 = random.nextInt(10)
print(number1,number2)
(2, 7)
addition_app = gateway.entry_point        # get the AdditionApplication instance
addition_app.addition(number1,number2)    # call the addition method


Math = gateway.jvm.java.lang.Math
a = Math.max(4, 6);
print a

IRI = gateway.jvm.org.semanticweb.owlapi.model.IRI

abcIRI = IRI.create('fewf#fe')
print 'abcIRi = ' + str(abcIRI)
print 'abcIRI.getFragment() = ' + abcIRI.getFragment()

The result on console is : 控制台上的结果是:

(5, 0)
6
abcIRi = fewf#fe
abcIRI.getFragment() = fe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM