package com.friday.executor.common;

import com.friday.operation.api.distributor.middleware.IPythonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author YaoYao
 * @Date Created In 11:17 2023/3/31
 * @Description
 * @Modified By
 */
@Slf4j
@Service
public class PythonHelper implements IPythonHelper {
    @Value("${python.exe.location}")
    private String pythonExecLocation;

    @Override
    public String runPython(String pythonPath, String... args){
        StringBuilder result = new StringBuilder();
        try {
            String cmds = pythonExecLocation + " " + pythonPath + " " + String.join(" ", args);
            log.info(cmds);
            Process pcs = Runtime.getRuntime().exec(cmds);
            pcs.waitFor();
            BufferedReader in = new BufferedReader(new InputStreamReader(pcs.getInputStream(),"GB2312"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e){
            log.error("运行python失败", e);
        }
        return result.toString();
    }

}
