从 TextIOWrapper 读取会导致 UnicodeDecodeError

Reading from TextIOWrapper causes UnicodeDecodeError

我尝试逐行读取子流程:

proc = subprocess.Popen(self.monitor_logcat_cmd, shell=True, stdout=subprocess.PIPE,
                        bufsize=1, universal_newlines=True)

while proc.poll() is None:
    line = proc.stdout.readline()
    print("Process line: " + str(line))

它有效,但有时我收到错误:

Exception in thread Thread-14:
Traceback (most recent call last):
  File "/Users/F1sherKK/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/F1sherKK/Dev/Python/AutomationTestSupervisor/session/SessionThreads.py", line 46, in run
    line = proc.stdout.readline()
  File "/Users/F1sherKK/anaconda3/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 89: invalid start byte

有什么方法可以add/specify 对子进程的标准输出进行编码吗?我想添加错误 "ignoring".

还有其他方法可以解决这个问题吗?

可以 errors 关键字参数设置为 Popen()'ignore'。来自 documentation:

If encoding or errors are specified, or universal_newlines is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper.

但是,您的进程显然没有使用 UTF-8 对其输出进行编码。您可能想弄清楚是否 a) 它可以配置为产生不同的编码,或者 b) 使用什么编码并配置它(使用 Popen()encoding 关键字参数)。