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

Python3.6使用subprocess.run遇UnicodeDecodeError错误求助

Python3.6下subprocess.run解码错误解决办法
  • 先检查并设置Python的默认编码
    Python3.6里subprocess的编码处理逻辑和3.9有差异,可能受系统默认locale影响。试试在脚本开头强制设置UTF-8编码的locale:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')  # 中文系统可以换成zh_CN.UTF-8
  • 不要同时用universal_newlines=True和encoding参数
    Python3.6中这两个参数混用可能触发兼容性问题,直接去掉universal_newlines=True,只保留编码设置:
smc_shell_script = subprocess.run(
    ['sh','smc.sh'], 
    stdout=subprocess.PIPE, 
    stderr=subprocess.STDOUT, 
    encoding='utf-8'
)
  • 手动处理字节流解码
    如果上面的方法没用,先以字节形式读取输出,再手动处理解码异常——要么尝试其他编码,要么忽略错误字符:
result = subprocess.run(
    ['sh','smc.sh'], 
    stdout=subprocess.PIPE, 
    stderr=subprocess.STDOUT
)
try:
    output = result.stdout.decode('utf-8')
except UnicodeDecodeError:
    # 用?替换无法解码的字符,或者换成对应编码比如gbk
    output = result.stdout.decode('utf-8', errors='replace')
    # 或者试试 output = result.stdout.decode('gbk')
  • 确认shell脚本的实际输出编码
    有些命令输出可能不是UTF-8,比如老工具可能用latin-1或GBK。可以在终端执行file -bi <(./smc.sh)查看输出的编码类型,再对应调整解码方式。

内容的提问来源于stack exchange,提问作者Shahar Hamuzim Rajuan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:25:16