使用python中的java库 [英] Using a java library from python

查看:156
本文介绍了使用python中的java库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python应用程序和Java应用程序。 python应用程序为java应用程序生成输入并在命令行上调用它。

I have a python app and java app. The python app generates input for the java app and invokes it on the command line.

我确信必须有一个更优雅的解决方案;就像使用JNI从Java调用C代码一样。

I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.

任何指针?
(仅供参考,我是Python新手)

Any pointers? (FYI I'm v. new to Python)

澄清(以长期问题为代价:道歉)
py app(我不拥有)以许多配置文件的形式获取用户输入。然后它通过插件机制将这些和农场工作转移到许多(隐藏的)工具上。我希望添加对旧版Java应用程序提供的功能的支持。

Clarification (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.

因此从java应用程序调用python应用程序是没有意义的无法在jython环境中运行py app(在JVM上)。

So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).

由于没有明显的机制,我认为简单的CL调用是最好的解决方案。

Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.

推荐答案

很抱歉重新确认该帖子,但没有接受答案......

Sorry to ressurect the thread, but there was no accepted answer...

您也可以使用 Py4J 。首页上有一个例子和很多文档,但实际上,你只需要从你的python代码中调用Java方法就好像它们是python方法一样:

You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway()                        # connect to the JVM
>>> java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
>>> other_object = java_object.doThat()
>>> other_object.doThis(1,'abc')
>>> gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

与Jython相反,Py4J在Python VM中运行,因此它始终与最新版本的Python最新,并且您可以使用在Jython上运行不正常的库(例如,lxml)。通信是通过套接字而不是JNI完成的。

As opposed to Jython, Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The communication is done through sockets instead of JNI.

免责声明:我是Py4J的作者

这篇关于使用python中的java库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆