Java直接调用Python

来源:互联网 发布:java调用go语言 编辑:程序博客网 时间:2024/05/18 23:26

使用Runtime.getRuntime()执行脚本文件,这种方式和.net下面调用cmd执行命令的方式类似。如果执行的Python脚本有引用第三方包的,建议使用此种方式。

[java] view plain copy
  1. Process proc = Runtime.getRuntime().exec("python  D:\\demo.py");    
  2. proc.waitFor();    

Java调用代码:

[java] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. public class Test5 {  
  5.         public static void main(String[] args){  
  6.                 try{  
  7.                         System.out.println("start");  
  8.                         Process pr = Runtime.getRuntime().exec("d:\\python27\\python.exe test.py");  
  9.                           
  10.                         BufferedReader in = new BufferedReader(new  
  11.                                 InputStreamReader(pr.getInputStream()));  
  12.                         String line;  
  13.                         while ((line = in.readLine()) != null) {  
  14.                             System.out.println(line);  
  15.                         }  
  16.                         in.close();  
  17.                         pr.waitFor();  
  18.                         System.out.println("end");  
  19.                 } catch (Exception e){  
  20.                             e.printStackTrace();  
  21.                         }  
  22.                 }  
  23. }  

test.py的文件内容为:

[python] view plain copy
  1. import sys  
  2. import urllib  
  3. print "hello"  
  4. 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

0 0