python3.x - Java calls python, and the python code stops automatically, and the reason cannot be found
習慣沉默
習慣沉默 2017-06-28 09:23:50
0
3
926
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

習慣沉默
習慣沉默

reply all (3)
Peter_Zhu

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:

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

      should be processed firstBgetInputStream()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:

      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 readinputStreamorerrorStreamfirst?

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!