Home  >  Q&A  >  body text

python3.x - Java calls python, and the python code stops automatically, and the reason cannot be found

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();

Calling python code takes a long time to execute. It is estimated to take several hours, about five or six hours. If you execute the Python command directly in the shell alone, there will be no problem; however, if you use java to call python in this way, there will be a problem: after a while, python will have no output. My way to determine whether python is running is to continuously write files, and every once in a while, write files to the file system. If you enter the python command directly into the shell, it is normal. Java calls python. After more than three hours, no files are generated, but using htop to check, the thread is still there. The operating environment is ubuntu

習慣沉默習慣沉默2669 days ago978

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-06-28 09:25:50

    Regarding the interaction between java and python, I can give you an idea, just for reference. I have done a project before, using socket, the mobile terminal is java script, the server is python, and then java sends strings to the python server for interaction. You can try.

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-28 09:25:50

    You can check out jython, which can directly execute python code in java

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-28 09:25:50

    There is a problem with this code:

    Process process = Runtime.getRuntime().exec(args);
    int exitValue = process.waitFor(); // A
    ... process.getInputStream() ...   // B
    

    should be processed first BgetInputStream() and then AwaitFor, because Java communicates with the program it calls through a pipe. If the pipe is not read in time, the called program will It is possible to block when writing to stdout.

    So the correct order is:

    Process process = Runtime.getRuntime().exec(args);
    ... process.getInputStream() ...   // B
    ... process.getErrorStream() ...   // C
    int exitValue = process.waitFor(); // A
    

    Leave another question:

    If the called program writes to stderr first and then to stdout, won’t it still block? Should Java read inputStream or errorStream first?

    reply
    0
  • Cancelreply