You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python subprocess调用PowerShell时出现编码错误问题

解决Python调用PowerShell特殊字符(如é)输出乱码的问题

方法一:强制PowerShell输出UTF-8编码

让PowerShell以UTF-8格式输出内容,Python端直接用UTF-8解码即可正确解析特殊字符:

import subprocess

# 通过命令指定输出编码为UTF-8
result = subprocess.run(
    [r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', '-Command', 'echo é | Out-String -Encoding utf8'],
    stdout=subprocess.PIPE
)
print(result.stdout.decode('utf-8').strip())

或者先设置PowerShell的全局输出编码再执行命令:

import subprocess

cmd = r'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; echo é'
result = subprocess.run(
    [r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', '-Command', cmd],
    stdout=subprocess.PIPE
)
print(result.stdout.decode('utf-8').strip())

方法二:匹配系统默认编码解码

Windows环境下,PowerShell默认输出编码通常为GBK(cp936),直接用该编码解码即可:

import subprocess

process = subprocess.Popen(
    [r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', 'echo é'],
    stdout=subprocess.PIPE
)
print(process.stdout.read().decode('gbk').strip())

如果是其他语言版本的Windows,可通过locale.getpreferredencoding()获取系统默认编码后再解码。

方法三:利用subprocess的encoding参数(Python 3.7+)

Python 3.7及以上版本的subprocess支持直接指定encoding参数,无需手动解码:

import subprocess

result = subprocess.run(
    [r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', 'echo é'],
    stdout=subprocess.PIPE,
    encoding='gbk'
)
print(result.stdout.strip())

替代subprocess的方法

可以使用pywin32库直接调用Windows API执行PowerShell命令,需先执行pip install pywin32安装依赖:

import win32com.client

ps = win32com.client.Dispatch("PowerShell.Application")
result = ps.CreatePipeline('echo é').Invoke()
print(result[0])

内容的提问来源于stack exchange,提问作者beneverest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:42:05