从subprocess.Popen解码stdout时解码错误

时间:2018-05-07 15:30:58

标签: python-3.x

当我尝试解码stdout.PIPE的行输出时,

string.decode()会抛出错误。错误消息是:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 8: invalid start byte

0x84应为字母'ä'。失败的行如下所示:

b' Datentr\x84ger in Laufwerk C: ist System'

我无法指出它。我已使用sys.stdout.encoding检查了编码,即utf-8

import subprocess
import re

prc = subprocess.Popen(["cmd.exe"], shell = False, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
prc.stdin.write(b"dir\n")
outp, inp = prc.communicate()

regex = re.compile(r"^.*(\d\d:\d\d).*$")

for line in outp.splitlines():
    match = regex.match(line.decode('utf-8'))#  <--- decode fails here.
    if match:
        print(match.groups())

prc.stdin.close()

1 个答案:

答案 0 :(得分:0)

CMD使用ISO-8859-15对文字进行编码。所以通过PIPE传入的文本需要使用ISO进行解码,即使python使用utf-8对stdout进行编码。

相关问题