使用Pyjnius 从python调用自定义Java方法

来源:互联网 发布:知其所以然的意思 编辑:程序博客网 时间:2024/04/30 01:16

目前从Python调用Java代码大致有3种方式</span>


Py4J Pyjnius JPypeA Python interpreter. Py4J has been tested with CPython 2.6, 2.7, and CPython 3.4.基于CythonPython 2.6.0Java 6.0+.http://py4j.sourceforge.net/index.htmlhttp://pyjnius.readthedocs.org/en/latest/http://jpype.sourceforge.net/不支持Java7,需要先启动JVMbingo2013年停止更新 


经过对比,选择Pyjnius方式。


1. 安装Cython.

可以选择pip安装,也可以源码安装。Windows安装很坑爹,需要安装mingw gcc,还需要改些文件,不建议使用,直接装linux吧

到 http://cython.org/下载最新的Cython,解压缩进入主目录后,python setup.py install


2. 安装Pyjnius

到https://github.com/kivy/pyjnius/ 下载pyjnius, 解压缩后进入主目录, python setup.py install


3. 使用Pyjnius

http://pyjnius.readthedocs.org/en/latest/api.html#jvm-options-and-the-class-path

这一段讲的很清楚,要想使用自定义的class/jar文件必须修改 CLASSPATH环境变量,否则会报错 (File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:13457)),

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">那么有下面几种方法</span>


1.将.class文件打包成jar,然后将CLASSPATH指定jar的路径

2.将.class文件路径指向CLASSPATH

3.通过jnius.config修改CLASSPATH


'''@author: aaron'''import os#1. os.environ['CLASSPATH'] = '/home/aaron/workspace/javatest.jar'#2. os.environ['CLASSPATH'] = '/home/aaron/workspace/JavaTest/bin'import jnius_config#3. jnius_config.set_classpath('.','/home/aaron/workspace/JavaTest/bin')from jnius import autoclassJavaTest = autoclass('com.aaron.JavaTest')
<span style="font-family: Arial, Helvetica, sans-serif;">javatest = JavaTest()</span>
javatest.hi()Stack = autoclass('java.util.Stack')stack = Stack()stack.push('hello')stack.push('world')print stack.pop()


Reference:

  1. http://www.hackzine.org/using-apache-tika-from-python-with-jnius.html
  2. https://hahamo.wordpress.com/2014/06/24/pyja-calling-java-from-python-part-2/


0 0