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
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.
You can check out jython, which can directly execute python code in java
There is a problem with this code:
should be processed firstB
getInputStream()
and thenAwaitFor
, 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:
Leave another question:
If the called program writes to stderr first and then to stdout, won’t it still block? Should Java read
inputStream
orerrorStream
first?