This question already has answers here:
process.waitFor() never returns
                                
                                    (10个回答)
                                
                        
                                2年前关闭。
            
                    
下面是我的代码。尝试执行python脚本,但是waitfor()从未完成。下面是我的代码。有什么建议么。

String[] command ={"CMD","C:\\Users\\vkode200\\IdeaProjects\\Pythonex1\\TestHello.py"};

         ProcessBuilder probuilder = new ProcessBuilder(command );
            //You can set up your work directory
            /*probuilder.directory(new File("c:\\xyzwsdemo"));*/

            Process process = probuilder.start();

            //Read out dir output
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            System.out.printf("Output of running %s is:\n",
                    Arrays.toString(command));
            /*while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
*/
            //Wait to get exit value
            try {
                 exitValue = process.waitFor();
                 /*exitValue= process.exitValue();*/
                System.out.println("\n\nExit Value is " + exitValue);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

最佳答案

您需要关闭进程的输入流,并在调用stdout之前在stderrwaitFor()上使用其所有输出。

否则,尝试读取您未发送的输入或产生您未读取的输出时,它可能会被阻止。

10-06 11:18