【发布时间】:2019-11-20 06:37:32
【问题描述】:
上下文
我有一个生成器,它不断输出特定命令的每一行(参见下面的代码 sn-p,代码取自 here)。
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
for stdoutLine in iter(popen.stdout.readline, ""):
yield stdoutLine.rstrip('\r|\n')
问题
问题是,stdout 行可能包含 cp1252 无法处理的特殊字符。 (请参阅下面的多条错误消息,每条都来自不同的测试)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 6210: character maps to <undefined>
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 3691: character maps to <undefined>
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 6228: character maps to <undefined>
问题
如何处理这些特殊字符?
【问题讨论】:
标签: python-3.x encoding special-characters decode popen