从J调用python脚本时获取输出的问题

2024-09-28 22:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Java程序来调用python脚本。我用了exec方法。请查找下面的代码片段:

Python程序(它是从wikipedia收集一部分文本)单独运行时,会给我正确的输出。从Java调用时,我无法从python程序获得完整的输出。在

我使用ready()方法检查了BufferedReader对象的状态(如所解释的here),代码进入了无限循环。在

我认为其他人也面临着类似的问题-https://stackoverflow.com/a/20661352/3409074

有人能帮我吗?在

      public String enhanceData(String name,String entity) {
            String s = null;
            StringBuffer output = new StringBuffer();
            try{
                String command="python C://enhancer.py "+name+" "+entity;
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((s = stdInput.readLine()) != null) {

                    System.out.println(s);
                    output.append(s);
                  }

Tags: 方法代码name程序newoutputstringjava
1条回答
网友
1楼 · 发布于 2024-09-28 22:30:26

while循环条件实际上已经读取了一行,因此每次循环中都要重复读取该行。在

while ((s = stdInput.readLine()) != null) {
    //s=stdInput.readLine();  <- don't need this
    System.out.println(s);
    output.append(s);
}

/尼克

相关问题 更多 >