프로그래밍/자바

자바에서 파이썬 파일 실행하고 결과 받아 오기

do121 2024. 2. 9. 22:06

자바에서 파일 받을 때 에러가 계속나서 포기하고 파이썬에서 받는 걸로 변경했다.

어차피 소스 자체를 파이썬으로 포팅할 거라 가능하면 파이썬으로 변경하기 위한 일환으로 작업함

 

파이썬은 C:\\Program Files\\Python37\\python.exe 에 설치했다는 가정하에

(3.10이후부터 ssl문제가 있어서 3.7인 3.9를 사용함)

 

아래와 같이 파이썬 코드를 실행하고 결과를 받아옴

원래 아나콘다에 가상환경을 만들어서 파이썬 작업을 하는데 가상환경은 제어가 힘들어서 포기하고 파이썬3.7을 추가 설치함. 환경변수 path에 추가해도 기존 아나콘다에 설치된 파이썬때문에 pip가 제대로 안되기 때문에 pip하려면 3.7이 설치된 폴더 경로로 이동 후 pip를실행해야 3.7에 패키지가 설치됨. 이것 때문에 또 한참 뻘짓함...

누군가는 시간 허비하지 않기를 바라며 작업 내용을 올려봄

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PythonRunner {
    public static String runPythonCode(String pythonCode, String... args) {
        try {
            // 파이썬 프로세스 실행
            List<String> command = new ArrayList<>(Arrays.asList("C:\\Program Files\\Python37\\python.exe", pythonCode));
            command.addAll(Arrays.asList(args));

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            // 파이썬 프로세스의 출력 스트림을 읽기 위한 BufferedReader 생성
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            // 프로세스 종료까지 대기
            process.waitFor();

            // 프로세스의 출력을 읽어와서 문자열로 변환
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }

            return result.toString().trim();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {

        // 추가 인수
        // String additionalArg1 = "arg1";
        // String additionalArg2 = "arg2";

    }
}

 

 

자바에서 아래와 같이 함수 호출함

PythonRunner.runPythonCode("E:\\download.py", Url,Path);

 

파이썬 코드는 아래와 같은 형태임

import requests
import argparse

def download(url, file_path):

    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0'

    headers = {'User-Agent': user_agent}
    response = requests.get(url, headers=headers, stream=True)
    
    if response.status_code == 200:
        with open(file_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=128):
                file.write(chunk)
        print(f"downloaded successfully: {file_path}")
    else:
        print(f"Failed to download. Status code: {response.status_code}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Download from a URL and save it to a file.")
    parser.add_argument("url", help="URL to download")
    parser.add_argument("file_path", help="Path to save the downloaded file")

    args = parser.parse_args()
    download_image(args.url, args.file_path)