使用python调用java-jpype

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/d12345678a/article/details/78562188

一、jpype

1.环境(我的电脑是windows 64位):

python2.7(32位),jdk1.5(32位),JPype-0.5.4.2.win32-py2.7.exe ,
https://sourceforge.net/projects/jpype/files/JPype/0.5.4/


2.测试:

#coding=utf-8  
#!/usr/bin/python  
import jpype
from jpype import *  
import os.path  


jvmPath = jpype.getDefaultJVMPath()  
if not jpype.isJVMStarted(): 
	jpype.startJVM(jvmPath,'-ea')  
#jarpath = os.path.join(os.path.abspath('.'), 'build/jar')       
#startJVM(r"D:\worktools\Java\jdk1.5\jre\bin\server\jvm.dll", "-ea")  
jpype.java.lang.System.out.println("Hello World")  
jpype.shutdownJVM()  

直接在cmd命令行执行python test.py就可以了



二、调用jar包

http://blog.csdn.net/newxren/article/details/7351200

我之前一直按照网上博客写的打jar包的方式调用执行,总是报找不到类的错误,python代码:

import jpype  
from jpype import *  
jvmPath = jpype.getDefaultJVMPath()  
ext_classpath = r'D:\work\workspace\out\artifacts\testjpype_jar\testjpype.jar'  
#jarpath = os.path.join(os.path.abspath('.'), 'F:/sample_Py/')  #os not found
jvmArg = '-Djava.class.path=%s'%ext_classpath  
print jvmArg  
if not jpype.isJVMStarted():  
    jpype.startJVM(jvmPath,'-ea',jvmArg)  
jpype.java.lang.System.out.println('Hello world!')  

javaClass = JClass("com.testjava")  
jd = javaClass()  
jprint = java.lang.System.out.println  
jprint(jd.sayHello("waw"))  
jprint(jd.calc(2,4))  

jpype.shutdownJVM()
报错:

    raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.ExceptionPyRaisable: java.lang.Exception: Class JpypeDemo not found

网上找了很多资料,基本就是说java代码中依赖的东西都需要在classpath下,但是我的java代码啥都没依赖啊,哭~~~~

但是很明显的就是class not found肯定是在某个目录下找不到需要的.class文件,然后我就在java文件目录下用javac编译出class文件,然后在当前执行:

D:\worktools\python2.7win32\workspace\com>python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from jpype import *
>>> startJVM(jpype.getDefaultJVMPath(),"-ea")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'jpype' is not defined
>>> import jpype
>>> from jpype import *
>>> jvmPath=jpype.getDefaultJVMPath()
>>> startJVM(jvmPath)
>>> JavaP = JClass("JpypeDemo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\worktools\python2.7win32\lib\site-packages\jpype\_jclass.py", line 54
, in JClass
    raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.ExceptionPyRaisable: java.lang.Exception: Class JpypeDemo not
found
>>> jpype.java.lang.System.out.println('Hello world!')(执行这一句是可以的)
Hello world!
>>> ^V

后来各种乱改瞎尝试,发现在java代码里面加上package:

package com;
public class JpypeDemo {
    private String str = "";
    public JpypeDemo() {
        this.str = "JpypeDemo Init";
    }
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }
}

用javac编译后,再到com的同级目录下执行下面的python代码就不再报错了:

import jpype  
from jpype import *  
jarpath = r'D:\worktools\python2.7win32\workspace'  
startJVM(jpype.getDefaultJVMPath(),"-ea", "-Djava.class.path=%s" % jarpath)  
JpypeDemo = jpype.JClass('com.JpypeDemo')
test = JpypeDemo()
res = test.getStr()
print res
jpype.shutdownJVM()

D:\worktools\python2.7win32\workspace>python D:\worktools\python2.7win32\workspa
ce\1120.py
JpypeDemo Init
JVM activity report     :
        classes loaded       : 20
JVM has been shutdown

 3.访问JAVA的系统属性

       假设你要设置的属性名为 yourProperty,属性值为 yourValue 。

 1)JVM启动时设置系统变量示例

import jpype 
 jvmPath = jpype.getDefaultJVMPath() 
 jvmArg = “ -DyourProperty=yourValue ”
 if not jpype.isJVMStarted(): 
    jpype.startJVM(jvmPath,jvmArg)

 2)在程序中设置系统变量示例

import jpype 
 prop = “ yourProperty ”
 value = “ yourValue ”
 system = jpype.JClass('java.lang.System') 
 system.setProperty(str(prop),str(value))

 3)在程序中获取系统变量示例

import jpype 
 prop = “ yourProperty ”
 system = jpype.JClass('java.lang.System') 
 value = system.getProperty(str(prop))

使用python3.5和jdk1.8的环境使用Jpype的介绍:https://liuliqiang.info/post/allthing-about-jpype/


三、其他python知识

这里介绍一下python执行shell命令的四种方法:

1、os模块中的os.system()这个函数来执行shell命令

1
2
3
>>> os.system( 'ls' )
anaconda - ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,这个方法得不到shell命令的输出。


2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。

1
2
3
4
5
>>>  import  os
>>>  str  =  os.popen( "ls" ).read()
>>> a  =  str .split( "\n" )
>>>  for  in  a:
         print  b

这样得到的结果与第一个方法是一样的。

3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位

1
2
3
4
5
6
7
8
9
10
11
12
import  commands
a,b  =  commands.getstatusoutput( 'ls' )
a是退出状态
b是输出的结果。
>>>  import  commands
>>> a,b  =  commands.getstatusoutput( 'ls' )
>>>  print  a
0
>>>  print  b
anaconda - ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回输出结果

commands.getstatus(file)返回ls -ld file 的执行结果字符串,调用了getoutput,不建议使用这个方法。


4、subprocess模块


使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

import subprocess

1、subprocess.call(command, shell=True)

#会直接打印出结果。

2、subprocess.Popen(command, shell=True) 也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就可以输出结果了。

如果command不是一个可执行文件,shell=True是不可省略的。

shell=True意思是shell下执行command


这四种方法都可以执行shell命令。







猜你喜欢

转载自blog.csdn.net/d12345678a/article/details/78562188