build.gradle 추가
implementation 'org.apache.commons:commons-exec:1.3'
java 소스코드
@GetMapping(value = "exe_python")
public String exePython() {
File file = new File("");
File rootPath = file.getAbsoluteFile();
System.out.println("현재 프로젝트의 경로 : "+rootPath );
System.out.println("Python Call");
String[] command = new String[4];
command[0] = "python3";
command[1] = rootPath+"/zz.py";
//command[1] = rootPath+"/id_card_data.py";
//command[2] = rootPath+"/test01.jpg";
command[2] = "10";
command[3] = "20";
int result;
String output = "";
try {
Map<String,Object> res = execPython(command);
result = (int) res.get("result");
output = (String) res.get("output");
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
public Map<String,Object> execPython(String[] command) throws IOException, InterruptedException {
CommandLine commandLine = CommandLine.parse(command[0]);
for (int i = 1, n = command.length; i < n; i++) {
commandLine.addArgument(command[i]);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(pumpStreamHandler);
int result = executor.execute(commandLine);
System.out.println("result: " + result);
System.out.println("output: " + outputStream.toString());
Map<String, Object> resMap = new HashMap<String, Object>();
resMap.put("result", result);
resMap.put("output", outputStream.toString());
return resMap;
}
'프로그래밍 > Java' 카테고리의 다른 글
java 스케쥴러 중복 실행될때 (0) | 2022.02.23 |
---|---|
Java 정규식 + split (0) | 2022.02.10 |
Intellij 추천 플러그인 (plugin) (0) | 2022.01.25 |
스프링 어노테이션 @Autowired 기본개념 (0) | 2022.01.20 |
mac java17 인텔리제이 자동 리로드 devtools 안될때 (0) | 2022.01.14 |