From e4fbc7fe694dfb728c7845f82f163e8c755772de Mon Sep 17 00:00:00 2001 From: 2Shirt <2xShirt@gmail.com> Date: Wed, 23 Jun 2021 23:30:19 -0600 Subject: [PATCH] Prevent 100% CPU usage in NonBlockingStreamReader --- scripts/wk/exe.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/wk/exe.py b/scripts/wk/exe.py index 29d4f967..ab49018b 100644 --- a/scripts/wk/exe.py +++ b/scripts/wk/exe.py @@ -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):