>  기사  >  Java  >  Java에서 Python을 호출하는 방법

Java에서 Python을 호출하는 방법

WBOY
WBOY앞으로
2023-05-17 12:08:122221검색

    Python 언어에는 풍부한 시스템 관리, 데이터 처리 및 통계 소프트웨어 패키지가 있으므로 Java 애플리케이션에서 Python 코드를 호출해야 하는 필요성은 매우 일반적이고 실용적입니다. DataX는 Alibaba가 오픈소스로 제공하는 이기종 데이터 소스를 위한 오프라인 동기화 도구로, 관계형 데이터베이스(MySQL, Oracle 등), HDFS, Hive, ODPS, HBase, FTP를 포함한 다양한 이기종 데이터 소스 간에 안정적이고 효율적인 데이터를 달성하는 데 전념하고 있습니다. 등 동기화 기능. Datax는 Java를 통해 Python 스크립트도 호출합니다.

    Java core

    Java는 ProcessBuilder API와 JSR-223 스크립팅 엔진이라는 두 가지 방법을 제공합니다.

    ProcessBuilder 사용

    ProcessBuilder를 통해 로컬 운영 체제 프로세스를 생성하여 Python을 시작하고 Python 스크립트를 실행합니다. hello.py 스크립트는 단순히 "Hello Python!"을 출력합니다. 개발 환경에는 Python이 설치되어 있고 환경 변수가 설정되어 있어야 합니다.

    @Test
    public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py"));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        List<String> results = readProcessOutput(process.getInputStream());
        assertThat("Results should not be empty", results, is(not(empty())));
        assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Python!")));
        int exitCode = process.waitFor();
        assertEquals("No errors should be detected", 0, exitCode);
    }
    private List<String> readProcessOutput(InputStream inputStream) throws IOException {
        try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
            return output.lines()
                .collect(Collectors.toList());
        }
    }
    private String resolvePythonScriptPath(String filename) {
        File file = new File("src/test/resources/" + filename);
        return file.getAbsolutePath();
    }

    이 문장을 다시 쓰려면 다음과 같이 말할 수 있습니다. Python 스크립트의 전체 경로인 하나의 인수를 사용하여 Python 명령을 사용하기 시작합니다. Java 프로젝트의 리소스 디렉터리에 배치할 수 있습니다. 주목해야 할 것은 스크립트를 실행할 때 오류가 발생할 때 오류 출력 스트림을 표준 출력 스트림에 병합하기 위한 RedirectErrorStream(true)입니다. 오류 정보는 Process 객체의 getInputStream() 메서드를 호출하여 읽을 수 있습니다. 이 설정이 없으면 스트림을 얻으려면 getInputStream() 및 getErrorStream()이라는 두 가지 메서드를 사용해야 합니다. ProcessBuilder에서 Process 개체를 가져온 후 출력 스트림을 읽어 결과를 확인합니다.

    Java 스크립트 엔진 사용

    JSR-223 사양은 Java 6에서 처음 도입되었으며 기본 스크립팅 기능을 제공할 수 있는 스크립팅 API 세트를 정의합니다. 이러한 API는 Java와 스크립팅 언어 간에 값을 공유하고 스크립트를 실행하기 위한 메커니즘을 제공합니다. 이 사양의 주요 목적은 Java와 다양한 JVM을 구현하는 동적 스크립팅 언어 간의 상호 작용을 통합하는 것입니다. Jython은 JVM에서 실행되는 Python의 Java 구현입니다. CLASSPATH에 Jython이 있다고 가정하면 프레임워크는 해당 스크립팅 엔진을 사용할 가능성이 있음을 자동으로 발견하고 Python 스크립팅 엔진을 직접 요청할 수 있도록 합니다. Maven에서는 Jython을 참조하거나 직접 다운로드하여 설치할 수 있습니다.

    <dependency>
        <groupId>org.python</groupId>
        <artifactId>jython</artifactId>
        <version>2.7.2</version>
    </dependency>

    다음 코드를 통해 지원되는 모든 스크립트 엔진을 나열할 수 있습니다.

    public static void listEngines() {
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> engines = manager.getEngineFactories();
        for (ScriptEngineFactory engine : engines) {
            LOGGER.info("Engine name: {}", engine.getEngineName());
            LOGGER.info("Version: {}", engine.getEngineVersion());
            LOGGER.info("Language: {}", engine.getLanguageName());
            LOGGER.info("Short Names:");
            for (String names : engine.getNames()) {
                LOGGER.info(names);
            }
        }
    }

    환경에서 Jython을 사용할 수 있는 경우 해당 출력이 표시됩니다.

    ...
    엔진 이름: jython
    버전: 2.7.2
    언어: python
    짧은 이름:
    python
    jython

    이제 Jython을 사용하여 hello.py 스크립트를 호출하세요.

    @Test
    public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception {
        StringWriter writer = new StringWriter();
        ScriptContext context = new SimpleScriptContext();
        context.setWriter(writer);
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("python");
        engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context);
        assertEquals("Should contain script output: ", "Hello Python!", writer.toString().trim());
    }

    이 API를 사용하는 것이 다음보다 더 간결합니다. 위의 예. ScriptContext를 설정할 때 스크립트 실행의 출력을 저장하려면 StringWriter를 포함해야 합니다. 그런 다음 ScriptEngineManager가 Python 또는 jython을 사용할 수 있는 스크립트 엔진을 찾을 수 있도록 짧은 이름을 제공합니다. 마지막으로 출력이 예상과 일치하는지 확인합니다.

    실제로 PythonInterpretor 클래스를 사용하여 내장된 Python 코드를 직접 호출할 수도 있습니다.

    @Test
    public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            StringWriter output = new StringWriter();
            pyInterp.setOut(output);
            pyInterp.exec("print(&#39;Hello Python!&#39;)");
            assertEquals("Should contain script output: ", "Hello Python!", output.toString().trim());
        }
    }

    PythonInterpreter 클래스에서 제공하는 exec 메소드를 사용하면 Python 코드를 직접 실행할 수 있습니다. 이전 예제와 같이 StringWriter를 통해 실행 출력을 캡처합니다. 또 다른 예를 살펴보겠습니다.

    @Test
    public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            pyInterp.exec("x = 10+10");
            PyObject x = pyInterp.get("x");
            assertEquals("x: ", 20, x.asInt());
        }
    }

    위의 예에서는 get 메소드를 사용하여 변수 값에 액세스할 수 있습니다. 다음 예에서는 오류를 잡는 방법을 보여줍니다.

    try (PythonInterpreter pyInterp = new PythonInterpreter()) {
        pyInterp.exec("import syds");
    }

    위 코드를 실행하면 PyException 예외가 발생합니다. 이는 Python 스크립트를 로컬에서 실행하여 오류를 출력하는 것과 같습니다.

    아래 참고할 몇 가지 사항:

    • PythonIntepreter는 AutoCloseable을 구현하며 try-with-resources와 함께 사용하는 것이 가장 좋습니다.

    • PythonIntepreter 클래스 이름은 Python 코드를 나타내는 파서가 아닙니다. Python 프로그램은 jvm의 Jython에서 실행되며 실행 전에 Java 바이트코드로 컴파일되어야 합니다.

    • Jython은 Java의 Python 구현이지만 기본 Python과 동일한 하위 패키지가 모두 포함되어 있지 않을 수 있습니다.

    다음 예에서는 Java 변수를 Python 변수에 할당하는 방법을 보여줍니다.

    import org.python.util.PythonInterpreter; 
    import org.python.core.*; 
    class test3{
        public static void main(String a[]){
            int number1 = 10;
            int number2 = 32;
            try (PythonInterpreter pyInterp = new PythonInterpreter()) {
                python.set("number1", new PyInteger(number1));
                python.set("number2", new PyInteger(number2));
                python.exec("number3 = number1+number2");
                PyObject number3 = python.get("number3");
                System.out.println("val : "+number3.toString());
            }
        }
    }

    위 내용은 Java에서 Python을 호출하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제