开发者

Java/Python: Integration, problem with looping updating text

开发者 https://www.devze.com 2022-12-29 15:11 出处:网络
Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the ch

Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the changes, so the output of the python will always be up to date with the window text.

I'm trying to access this text in my Java program by executing the python script as a process and reading the text it outputs using a buffered reader.

For some reason this works fine for the first block of text, but will not read any more after this, it wont read any updates to the text as the python outputs it.

Can someone shed some light on 开发者_如何学编程this? I'm about to try and use Jython, but I'd really like to know what the problem is here...

try {
  Runtime r = Runtime.getRuntime();
  Process p = r.exec("cmd /c getText.py");
  BufferedReader br = new BufferedReader(
                                new InputStreamReader(p.getInputStream()));
  int line;
  while (true) {
    line = br.read();
    System.out.print((char) line);
  }
} catch (Exception e) {
    e.printStackTrace();
}


I think I was able to reproduce your error by writing a simple python program to print random numbers and then sleep:

import random
import time
import sys

random.seed(time.time())

print 'starting random numbers'
#sys.stdout.flush()
print 'big block of text' * 2000
#sys.stdout.flush()

count = 3

while count > 0:
    sleeper = random.randint(1, 5)
    r = random.randint(1000, 9000)
    print r, 'sleeping for', sleeper, 'seconds'
    #sys.stdout.flush()
    time.sleep(sleeper)
    count -= 1

print 'random numbers finished, closing'
#sys.stdout.flush()

The interesting bit here is that the java code will echo the first few prints but will then wait until the program is finished before it prints the rest. The problem with this example code is that the output from the Python script is buffered in stdout so the Java app can't read it. It works correctly when you uncomment the sys.stdout.flush() commands.

I would try adding a flush() to your python program and see if that fixes the issue.

0

精彩评论

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

关注公众号