Java直接调用Python
使用Runtime.getRuntime()执行脚本文件,这种方式和.net下面调用cmd执行命令的方式类似。如果执行的Python脚本有引用第三方包的,建议使用此种方式。
[java] view plain copy
- Process proc = Runtime.getRuntime().exec("python D:\demo.py");
- proc.waitFor();
Java调用代码:
[java] view plain copy
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class Test5 {
- public static void main(String[] args){
- try{
- System.out.println("start");
- Process pr = Runtime.getRuntime().exec("d:\python27\python.exe test.py");
- BufferedReader in = new BufferedReader(new
- InputStreamReader(pr.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- System.out.println(line);
- }
- in.close();
- pr.waitFor();
- System.out.println("end");
- } catch (Exception e){
- e.printStackTrace();
- }
- }
- }
test.py的文件内容为:
[python] view plain copy
- import sys
- import urllib
- print "hello"
- print sys.path
java程序运行的结果为:
start
hello
["D:\eclipse_jee_workspace\ZLabTest", "C:\Windows\system32\python27.zip", "D:\Python27\DLLs", "D:\Python27\lib", "D:\Python27\lib\plat-win", "D:\Python27\lib\lib-tk", "D:\Python27", "D:\Python27\lib\site-packages"]
end
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 在Java中调用Python
- 下一篇: Yii2底层源码解读系列之一 入口文件index.php