java执行python脚本

亲测 ok 不带参数的

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

 

 

public class Deno2 {

 public static void main(String[] args) throws IOException, InterruptedException {

  String[] arguments = new String[] {"python", "/Users/lucax/Desktop/test实验室2/b.py"};

 

  //打开文件执行和读取输出字符

        try {

            Process process = Runtime.getRuntime().exec(arguments);

          //这段代码中的GBK是为了防止Python输出中文时乱码加的。

            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));

            String line = null;

         while ((line = in.readLine()) != null) {  

             System.out.println(line);  

         }  

         in.close();

         //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,

        //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反

         int re = process.waitFor();  

         System.out.println(re);

        

        } catch (Exception e) {

     

        }  

 }

}


 

参考: https://blog.csdn.net/wl_Honest/article/details/84340944

原文地址:https://www.cnblogs.com/kaibindirver/p/12146215.html