I have inherited code that enters a busy loop reading the output of a subprocess looking for a keyword, but I would like it to work with lower overhead. The code is as follows:
def stdout_search(self, file, keyword)
s = ''
while True:
c = file.read(1)
if not c:
return None
if c != '\r' and c != '\n':
s += c
continue
s = s.strip()
if keyword in s:
break
s = ''
i = s.find(keyword) + len(keyword)
return s[i:]
def scan_output(self, file, ev)
while not ev.wait(0):
s = self.stdout_search(file, 'Keyword:')
if not s:
break
# Do something useful with s
offset = #calculate offset
wx.CallAfter(self.offset_label.SetLabel offset)
#time.sleep(0.03)
The output from the Popen
ed process is something like:
Keyword: 1 of 100
Keyword: 2 of 100
...etc...
Uncommenting the time.sleep(0.03)
at the end of scan_output
takes the load on a single core down from 100% to an acceptable 25% or so, but unfortunately the offset label redraw stutters, and although I am reading a frame count from a 30 fps playback, the label often updates less than once a second. How can I implement this code with a more correct wait for input?
BTW, the full code may be found here.