Java直接调用Python

来源:互联网 发布:淘宝店铺出租风险 编辑:程序博客网 时间:2024/06/09 22:51

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

Process proc = Runtime.getRuntime().exec("python  D:\\demo.py");  proc.waitFor();  

Java调用代码:

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的文件内容为:

import sysimport urllibprint "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



0 0