开发者

Java: BufferedReader reads self-updating shell-output from a Python Script and regexes live, updates every 5 sec

开发者 https://www.devze.com 2023-03-20 02:03 出处:网络
The problem is this: I have a Python Script which generates Shell output. This output looks like this:

The problem is this: I have a Python Script which generates Shell output. This output looks like this:

Result: good.

[123 SPEED] [456 GOOD] [789 BAD]

The last line updates itself and becomes either a result:good or result:bad line. Then again the last line updates itself and erases the previous one. I found a way how to disable this behaviour in the python script, but it would be nice to only regex the last line of the shell output w/o alt开发者_Python百科ering the python script.

Now if I let run this Java code over that output, it display not the wanted results, if any.

The timer runs like I expect it for the first 3 times, then it stops for 1 minute and then outputs 50 lines of regexed output and even the wrong one.

The desired result is to output the first bracket, the second bracket and the third bracket into distinct GUI Swing labels and then update these labels every n seconds from the python shell output.

        try {
            p = Runtime.getRuntime().exec("myScript.py -Switches");
            pReg = Pattern.compile("\\[(.*?)\\]");
            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
            exec.scheduleAtFixedRate(new Runnable() {
              @Override
              public void run() {
                   try {
                      BufferedReader input =
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
                        if ((line = input.readLine()) != null) {
                            // regex
                            Matcher m = pReg.matcher(line);
                            int h = 0;
                            while(m.find()) {
                               myHashArray[h] = m.group(1);
                               h++;
                               Sytem.out.println(m.group(1));
                            }
                        }
                  }
                   catch (IOException e1) {
                        System.err.println(e1);
                        System.exit(1);
                   }
                }
            }, 0, 500, TimeUnit.MILLISECONDS);
        }

        catch (IOException ea) {
            System.exit(0);
        }


Try not using a BufferedReader -- use the InputStreamReader directly--

Or have the python process output new lines between each bracketed item

The BufferedStreamReader is waiting for the buffer to fill or for a new line before it returns anything to your Java process

0

精彩评论

暂无评论...
验证码 换一张
取 消