常见的java调用python脚本方式有两种,下面给大家介绍一下:
·通过Jython.jar提供的类库实现
·通过Runtime.getRuntime()开启进程来执行脚本文件
python学习网,大量的免费python视频教程,欢迎在线学习!
这两种方法我都尝试过,个人推荐第二种方法,因为Python有时需要用到第三方库,比如requests,而Jython不支持。所以本地安装Python环境并且安装第三库再用Java调用是最好的方法。
相关推荐:《Python基础教程》
下面通过两个小例子,分别是不带参数和带参数的,展示如何使用Java调用Python脚本:
Python代码:
defhello(): print('Hello,Python') if__name__=='__main__': hello()
Java代码:
importjava.io.BufferedReader; importjava.io.InputStreamReader; publicclassHelloPython{ publicstaticvoidmain(String[]args){ String[]arguments=newString[]{"python","E://workspace/hello.py"}; try{ Processprocess=Runtime.getRuntime().exec(arguments); BufferedReaderin=newBufferedReader(newInputStreamReader(process.getInputStream(), "GBK")); Stringline=null; while((line=in.readLine())!=null){ System.out.println(line); } in.close(); //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功, //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反 intre=process.waitFor(); System.out.println(re); }catch(Exceptione){ e.printStackTrace(); } } }
其中说明一点,BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));这段代码中的GBK是为了防止Python输出中文时乱码加的。
运行结果:
接下来是带参数的,Python代码:
importsys defhello(name,age): print('name:'+name) print('age:'+age) if__name__=='__main__': hello(sys.argv[1],sys.argv[2])
Java代码:
importjava.io.BufferedReader; importjava.io.InputStreamReader; publicclassHelloPython{ publicstaticvoidmain(String[]args){ String[]arguments=newString[]{"python","E://workspace/hello.py","lei","23"}; try{ Processprocess=Runtime.getRuntime().exec(arguments); BufferedReaderin=newBufferedReader(newInputStreamReader(process.getInputStream(), "GBK")); Stringline=null; while((line=in.readLine())!=null){ System.out.println(line); } in.close(); //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功, //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反 intre=process.waitFor(); System.out.println(re); }catch(Exceptione){ e.printStackTrace(); } } }
运行结果:
下一篇