@Slf4j
@Component
public class PythonUtils {
private static final String pyInterpreterPath = "python";
private static String pyPath="xxx.py";
private static String jsonPath="xxx.json";
public void setPyPath(String pyPath){
PythonUtils.pyPath = pyPath;
}
public void setJsonPath(String jsonPath){
PythonUtils.jsonPath = jsonPath;
}
public static String execPy() {
try {
String[] arguments = new String[] {pyInterpreterPath, pyPath, jsonPath};
// 执行脚本
Process proc = Runtime.getRuntime().exec(arguments);
// 获取返回值
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),"GBK"));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = in.readLine()) != null) {
builder.append(line);
}
in.close();
//返回0:成功。
int re = proc.waitFor();
System.out.println(re);
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
}