프로그래밍/Java

아주 쉬운 Java 에서 Python 호출 방법

소행성왕자 2022. 2. 10. 15:44

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;
}