首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么使用universal_newlines打开子进程会导致unicode解码异常?

为什么使用universal_newlines打开子进程会导致unicode解码异常?
EN

Stack Overflow用户
提问于 2015-03-11 18:24:47
回答 1查看 5.5K关注 0票数 3

我使用子进程模块运行子作业,并使用subprocess.PIPE收集子作业的输出流和错误流。为了避免死锁,我在一个单独的线程上不断地从这些流中读取。这是可行的,除非程序有时会因为解码问题而崩溃:

‘`UnicodeDecodeError:'ascii’编解码器无法解码位置483的字节0xe2 :序数不在范围内(128)

在较高的级别上,我了解Python可能试图使用ASCII编解码器转换为字符串,而且我需要在某个地方调用解码,我只是不确定在哪里。在创建子流程作业时,我指定universal_newlines为True。我认为这意味着,将stdout/stderr作为unicode返回,而不是二进制:

代码语言:javascript
复制
self.p = subprocess.Popen(self.command, shell=self.shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

崩溃发生在我的读取线程函数中:

代码语言:javascript
复制
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已经返回了解码数据。

这里发生了什么,我能做些什么来纠正这个问题?

这是完整的回溯

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2018-06-24 05:34:18

maby很好

代码语言:javascript
复制
 `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)`
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28994507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档