JAVA调用Python,并传递参数
在日常代码编写中,python语言比较方便,集成到项目时,java可以利用Runtime方法调用python并传递参数,代码如下:
如果调用的java代码比较简单,则可以省略环境路径——python.exe路径。如果python代码依赖环境复杂,有很多外部库,则要加上配置的环境路径。第二个路径为项目需要调用的py文件路径。integers为需要传递的参数。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入需要传递给python的参数");
String integers = input.nextLine();
String[] cmds = new String[]{"E:\\anaconda3\\python.exe", "E:project\\项目.py ",integers};
System.out.println("调用python程序");
Process pcs;
try {
pcs = Runtime.getRuntime().exec(cmds);
pcs.waitFor();
// 定义Python脚本的返回值
String result = null;
// 获取CMD的返回流
BufferedInputStream in = new BufferedInputStream(pcs.getInputStream());
// 字符流转换字节流
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// 这里也可以输出文本日志
String lineStr = null;
// System.out.println(br.readLine());
while ((lineStr = br.readLine()) != null) {
result = lineStr;
// System.out.println(br.readLine());
System.out.println(result);
}
//
// 关闭输入流
br.close();
in.close();
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}