python3.x - java調用python,python代碼自動停止了,找不到原因
問題描述
String[] args = {'python3', pythonFile};Process process = Runtime.getRuntime().exec(args);int exitValue = process.waitFor();BufferedInputStream in = new BufferedInputStream(process.getInputStream());BufferedInputStream err = new BufferedInputStream(process.getErrorStream());BufferedReader inBr = new BufferedReader(new InputStreamReader(in));BufferedReader errBr = new BufferedReader(new InputStreamReader(err));String lineStr;while ((lineStr = inBr.readLine()) != null) { logger.info(lineStr);}while ((lineStr = errBr.readLine()) != null) { logger.error(lineStr);}inBr.close();errBr.close();in.close();err.close();
調用python代碼,執行時間比較長,估計有好幾個小時,大概五六個小時。如果單獨直接在shell中執行Python命令,則不會出問題;但是,使用這種方式java調用python,就有問題:一段時間之后,python沒有輸出了。判斷python是否正在運行,我的方式是:不斷寫文件,每隔一段時間,寫文件到文件系統中。如果是直接shell中輸入python命令執行,那么是正常的。java調用python,三個多小時之后,就沒有產生文件了,但是使用htop查看,線程還在。運行環境是ubuntu
問題解答
回答1:對于java和python的交互,我倒是可以給你一個思路,僅做參考。我之前做過一個項目,使用的是socket,手機端是java腳本,服務端是python,然后java向python服務端發送字符串進行交互。你可以試試。
回答2:你可以去看看jython,可以在java中直接執行python代碼
回答3:這段代碼有個問題:
Process process = Runtime.getRuntime().exec(args);int exitValue = process.waitFor(); // A... process.getInputStream() ... // B
應該是先處理BgetInputStream()再處理AwaitFor,因為Java跟它調用的程序是通過管道(pipe)通訊的,如果不及時讀取管道,被調用的程序在寫stdout時就有可能阻塞住。
所以正確的順序是:
Process process = Runtime.getRuntime().exec(args);... process.getInputStream() ... // B... process.getErrorStream() ... // Cint exitValue = process.waitFor(); // A
另外留下個問題:
如果被調用程序先寫stderr再寫stdout,不還是會阻塞嗎?Java到底應該先讀inputStream還是先讀errorStream呢?
