首页 > 解决方案 > Python子进程解码特殊字符

问题描述

我正在使用subprocess. 问题是我无法按预期获取/解码正确的文本。

特殊字符在使用过程中在某处被错误解码/编码subprocess

当我直接从控制台执行 powershell 脚本时,数据是完整的(尽管它没有正确显示)。

在此处输入图像描述

如果我复制输出并将其粘贴到记事本中,我可以看到正确的文本。所以手动执行时没有问题。

在此处输入图像描述

现在,使用 执行此操作时subprocess,输出数据不正确。

import subprocess

process = subprocess.Popen(
    ['powershell', 'd:\\files_list.ps1'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
)
output, error = process.communicate()
print(output.decode('utf-8', 'ignore'))

在此处输入图像描述

我尝试了各种解码选项(cp1252, cp437),但我无法为这两行获得正确的文本。在解码字节流时使用默认值utf-8会引发异常。

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

我的猜测是标准输出字节流本身是不正确的。下面是output字节串的值。我们可以看到第一行已经带有?标记。

b'H:\\sc\\tamil ????????? - Copy.txt\r\nH:\\sc\\\x85, \x8a, \x8d, \x95, \x97,\x85, \x8a, \x8d, \x95.txt\r\n'

有人可以帮助捕获正确的输出吗?

标签: pythonpowershellsubprocess

解决方案


推荐阅读