封装工具类
package com.zrh.learn.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author: xiaozhang
* @date: 2021/1/28 14:28
*/
public class ProcessUtils {
public static String execProcess(String cmdStr) {
Process process = null;
String result = "";
try {
process = Runtime.getRuntime().exec(cmdStr);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result = line;
}
in.close();
process.waitFor();
return result;
} catch (Exception e) {
e.printStackTrace();
return result;
} finally {
process.destroy();
}
}
}
测试一下
@Test
void contextLoads() {
String cmdstr = "python3 /Users/xiaozhang/work/python/demo1.py 小强";
String s = ProcessUtils.execProcess(cmdstr);
System.out.println(s); // 输出: 你好,小强
}
demo1.py
import sys
name=sys.argv[1]
s='你好,'+name
print(s)