p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while p.poll() isNone: for line initer(p.stdout.readline, b''): print("output: %s" % line.rstrip().decode('utf8'))
defcustomized_readline(stream, delimiter, buffersize=1): lines = [b''] for data initer(lambda: stream.read(buffersize), b''): lines = re.split(delimiter, lines[-1] + data) for line in lines[:-1]: yield line yield lines[-1]
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) while p.poll() isNone: for line in customized_readline(p.stdout, b'\n|\r'): print("output: %s" % line.decode('utf8'))
Traceback (most recent call last): File "b.py", line 20, in <module> print("output: %s" % line.decode('utf8')) UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 98-99: unexpected end of data
import shlex import subprocess import re from codecs import iterdecode
defiter_unicode_chunks(byte_stream, encoding='utf-8'): binary_chunks = iter(lambda: byte_stream.read(1), b'') for unicode_chunk in iterdecode(binary_chunks, encoding): yield unicode_chunk
defcustomized_readline(iter_chunk_stream, delimiter): lines = [''] for data in iter_chunk_stream: lines = re.split(delimiter, lines[-1] + data) for line in lines[:-1]: yield line yield lines[-1]
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) while p.poll() isNone: for line in customized_readline(iter_unicode_chunks(p.stdout), '\r|\n'): print("output: %s" % line)