# java中调用终端命令,调用本地的python脚本文件
最近项目中,要调用Python脚本,并拿到对应的结果,参考网上的例子,最简单的实现是 Runtime.getRuntime().exec开一个子线程,可以使用绝对路径;如果不加任何前缀,默认为当前项目路径下执行;展示再windows下调用;同理再linux下调用只需要修改命令就行了;这里要主要注意:就会导致缓冲区占满,从而导致进程阻塞,Process.getInputStream()和Process.getErrorStream()分别返回Process的标准输出流和错误流,两个流如果处理不当,其缓冲区不能被及时清除而被塞满,则进程被阻塞,即使调用Process.destory()也未必能销毁被阻塞的子进程。
简单调用例子:
String cmd = " cmd /c dir ";
// String cmd = "python ./data/test.py";
try {
// Process process = Runtime.getRuntime().exec(cmd,null,new File("D:\\test"));
Process process = Runtime.getRuntime().exec(cmd,null, new File("ecg-date-file\\data"));
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
BufferedReader br = new BufferedReader(isr);
String content = br.readLine();
while (content != null) {
System.out.println(content);
content = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
防止阻塞例子
public static void main(String[] args) {
try{
System.out.println("start");
//一定要用虚拟环境下的python路径
String[] args1=new String[]{"D:\\SoftWare\\Anaconda\\envs\\jst\\python.exe","F:\\Python_Project\\test.py"};
Process pr = Runtime.getRuntime().exec(args1);
// 防止缓冲区满, 导致卡住
new Thread() {
@Override
public void run() {
super.run();
String line;
try {
BufferedReader stderr = new BufferedReader(new InputStreamReader(pr.getErrorStream(),"GBK"));
while ((line = stderr.readLine()) != null) {
System.out.println("stderr:" + line);
}
}
catch (Exception e) {
}
}
}.start();
System.out.println("==============打印结果==============");
new Thread() {
@Override
public void run() {
super.run();
String line;
try {
BufferedReader stdout = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));
while ((line = stdout.readLine()) != null) {
System.out.println("stdout:" + line);
}
}
catch (Exception e) {
}
}
}.start();
int exitVal = pr.waitFor();
if (0 != exitVal) {
System.out.println("执行脚本失败");
}
System.out.println("执行脚本成功");
} catch (Exception e){
e.printStackTrace();
}
}
参考的文章链接
https://blog.csdn.net/jstlovely/article/details/121247764?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-121247764-blog-112877855.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-121247764-blog-112877855.pc_relevant_antiscanv2&utm_relevant_index=1