Python使用subprocess调用PowerShell脚本特殊字符解码错误如何解决
解决方法
问题根源
- PowerShell 非交互模式下默认使用系统本地ANSI编码输出内容,而非UTF-8,编码不匹配直接导致解码报错
- 你看到的字节流中的
?和异常字节,是PowerShell输出时用默认编码无法识别特殊字符,提前替换为了占位符,属于源头输出错误,不是解码阶段能完全修复的
修复方案
方案1:强制PowerShell输出UTF-8编码内容(最稳定,推荐)
修改subprocess调用的PowerShell参数,先修改控制台输出编码为UTF-8后再执行脚本,Python端直接用UTF-8解码即可,修改后的代码如下:
import subprocess process = subprocess.Popen( ['powershell', '-Command', '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; & "d:\\files_list.ps1"'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) output, error = process.communicate() print(output.decode('utf-8'))
方案2:使用系统默认ANSI编码解码
如果不方便修改PowerShell调用参数,可以直接获取当前系统的默认ANSI编码进行解码:
import subprocess import locale # 获取系统默认编码 system_encoding = locale.getpreferredencoding() 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(system_encoding))
注意:该方案仅能修复解码阶段的错误,如果PowerShell输出时已经因为编码不支持把特殊字符替换为占位符,解码后仍然会存在乱码
内容的提问来源于stack exchange,提问作者Aakash Chakravarthy
相关产品推荐
相关产品推荐

