2017-12-28 1 views
0

현재 저는 GUI와 Python 스크립트가 Java 프로그램을 사용하여 프로젝트의 주요 기능을 수행하는 프로젝트를 진행하고 있습니다.Java를 사용하여 Python 응용 프로그램을 실행 한 다음 해당 출력을 구문 분석하십시오.

응용 프로그램 디렉토리에서 파이썬 스크립트를 실행하고 구문 분석을 위해 GUI 프로그램에 출력을 보내는 방법이 있는지 궁금합니다. 출력은 JSON/YAML/Plaintext 등일 수 있습니다 (GUI에서 파싱됩니다).

두 가지 옵션 내가 (또는 작동하지 않을 수있다)의 생각이었다 :

  1. 별도로 파이썬 프로그램을 실행하고 가진이이 다음 (Java 프로그램 읽을 수있는 파일입니다 출력 내 가장 좋아하는 것)
  2. 파이썬 프로그램을 실행하려면 ProcessBuilder 또는 Runtime.exec을 사용하십시오.하지만 어떻게 출력을 얻을 수 있습니까?

내가 생각한 내 옵션 중 어느 것도 적합하지 않거나 잘 작동하지 않는다면이 방법을 훨씬 개선 할 수 있을까요?

감사합니다.

+1

두 가지 모두 작동하지만 'ProcessBuilder # redirectOutput (Redirect)'및 'redirectError'를 선호합니다. 스트림으로부터 독해를 위해서 (때문에) 개별의 thread를 사용합니다. 그렇지 않으면, 출력 버퍼를 채운 후에 프로세스가 행해지는 일이 있습니다. – maaartinus

답변

1

Runtime.exec은 출력을 구문 분석하기 위해 버퍼링 된 판독기에 랩핑 할 수있는 입력 스트림을 제공합니다.

 try { 

     Process p = Runtime.getRuntime().exec("python 1.py'"); 

     BufferedReader stdInput = new BufferedReader(new 
      InputStreamReader(p.getInputStream())); 

     BufferedReader stdError = new BufferedReader(new 
      InputStreamReader(p.getErrorStream())); 

     // read the output from the command 
     System.out.println("Here is the standard output of the command:\n"); 
     while ((s = stdInput.readLine()) != null) { 
      System.out.println(s); 
     } 

     // read any errors from the attempted command 
     System.out.println("Here is the standard error of the command (if any):\n"); 
     while ((s = stdError.readLine()) != null) { 
      System.out.println(s); 
     } 

     System.exit(0); 
    } 
    catch (IOException e) { 
     System.out.println("exception happened - here's what I know: "); 
     e.printStackTrace(); 
     System.exit(-1); 
    } 
+0

귀하의 예는 명확하지 않습니다. 나에게 그것은'write.txt'라는 파일에서 당신의 독서처럼 보이기 때문에 실제로 출력을 얻기 위해 파이썬 스크립트를 효과적으로 실행할 수 있는지에 대한 제 질문에는 실제로 대답하지 않습니다 – rshah

관련 문제