Skip to content
Snippets Groups Projects
Commit be5492b3 authored by Jorrit Schaap's avatar Jorrit Schaap
Browse files

Task #9931: added non-blocking readlines method

parent 8018b3a5
Branches
Tags
No related merge requests found
import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
from threading import Thread from threading import Thread
try: try:
...@@ -5,6 +6,8 @@ try: ...@@ -5,6 +6,8 @@ try:
except ImportError: except ImportError:
from queue import Queue, Empty # python 3.x from queue import Queue, Empty # python 3.x
logger = logging.getLogger()
class PipeReader: class PipeReader:
''' '''
helper class to do non-blocking readline calls to a subprocess stdput or stderr pipe. helper class to do non-blocking readline calls to a subprocess stdput or stderr pipe.
...@@ -24,7 +27,7 @@ class PipeReader: ...@@ -24,7 +27,7 @@ class PipeReader:
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
def readline(self, timeout=None): def __fill_line_buffer(self, timeout=None):
start = datetime.now() start = datetime.now()
while timeout==None or datetime.now() - start <= timedelta(seconds=timeout): while timeout==None or datetime.now() - start <= timedelta(seconds=timeout):
try: try:
...@@ -34,6 +37,9 @@ class PipeReader: ...@@ -34,6 +37,9 @@ class PipeReader:
except Empty: except Empty:
pass pass
def readline(self, timeout=None):
self.__fill_line_buffer(timeout)
endline_idx = self.__line_buffer.find('\n') endline_idx = self.__line_buffer.find('\n')
if endline_idx > -1: if endline_idx > -1:
...@@ -42,3 +48,12 @@ class PipeReader: ...@@ -42,3 +48,12 @@ class PipeReader:
return line return line
return '' return ''
def readlines(self, timeout=None):
self.__fill_line_buffer(timeout)
lines = self.__line_buffer.split('\n')
if lines and not lines[-1].endswith('\n'):
self.__line_buffer = lines[-1]
lines = lines[:-2]
return lines
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment