我使用子进程模块运行子作业,并使用subprocess.PIPE收集子作业的输出流和错误流。为了避免死锁,我在一个单独的线程上不断地从这些流中读取。这是可行的,除非程序有时会因为解码问题而崩溃:
‘`UnicodeDecodeError:'ascii’编解码器无法解码位置483的字节0xe2 :序数不在范围内(128)
在较高的级别上,我了解Python可能试图使用ASCII编解码器转换为字符串,而且我需要在某个地方调用解码,我只是不确定在哪里。在创建子流程作业时,我指定universal_newlines为True。我认为这意味着,将stdout/stderr作为unicode返回,而不是二进制:
self.p = subprocess.Popen(self.command, shell=self.shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)崩溃发生在我的读取线程函数中:
def standardOutHandler(standardOut):
# Crash happens on the following line:
for line in iter(standardOut.readline, ''):
writerLock.acquire()
stdout_file.write(line)
if self.echoOutput:
sys.stdout.write(line)
sys.stdout.flush()
writerLock.release()还不清楚为什么readline在这里抛出解码异常;正如我所说的,我认为universal_newlines为true已经返回了解码数据。
这里发生了什么,我能做些什么来纠正这个问题?
这是完整的回溯
Exception in thread Thread-5:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/Users/lzrd/my_process.py", line 61, in standardOutHandler
for line in iter(standardOut.readline, ''):
File "/Users/lzrd/Envs/my_env/bin/../lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 483: ordinal not in range(128)发布于 2018-06-24 05:34:18
maby很好
`process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, encoding='utf-8') out, err = process.communicate() print('out: ') print(out) print('err: ') print(err)`https://stackoverflow.com/questions/28994507
复制相似问题