Prevent 100% CPU usage in NonBlockingStreamReader

This commit is contained in:
2Shirt 2021-06-23 23:30:19 -06:00
parent d76dca8fd7
commit e4fbc7fe69
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C

View file

@ -32,8 +32,12 @@ class NonBlockingStreamReader():
def populate_queue(stream, queue):
"""Collect lines from stream and put them in queue."""
while True:
line = stream.read(1)
while not stream.closed:
try:
line = stream.read(1)
except ValueError:
# Assuming the stream was closed
line = None
if line:
queue.put(line)
@ -42,6 +46,10 @@ class NonBlockingStreamReader():
args=(self.stream, self.queue),
)
def stop(self):
"""Stop reading from input stream."""
self.stream.close()
def read(self, timeout=None):
"""Read from queue if possible, returns item from queue."""
try:
@ -62,6 +70,9 @@ class NonBlockingStreamReader():
with open(out_path, 'a') as _f:
_f.write(out_bytes.decode('utf-8', errors='ignore'))
# Close stream to prevent 100% CPU usage
self.stream.close()
# Functions
def build_cmd_kwargs(cmd, minimized=False, pipe=True, shell=False, **kwargs):