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

《笨办法学Python》练习23:UnicodeEncodeError问题求助

解决Windows Git Bash中Python运行UnicodeEncodeError问题

我是Python新手,正在完成《笨办法学Python》的练习23,在Windows系统的Git Bash中运行代码时出现UnicodeEncodeError错误,不确定是代码问题还是系统Unicode设置问题。

我的代码

import sys
script, input_encoding, error = sys.argv


def main(language_file, encoding, errors):
    line = language_file.readline()

    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)


def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors=errors)
    cooked_string = raw_bytes.decode(encoding, errors=errors)

    print(raw_bytes, "<===>", cooked_string)


languages = open("languages.txt", encoding="utf-8")

main(languages, input_encoding, error)

报错信息(翻译后)

UnicodeEncodeError:'gbk' 编码无法编码特定位置的字符:非法多字节序列

问题原因与解决方案

问题出在Windows的Git Bash默认使用GBK编码作为终端输出编码,但脚本输出包含UTF-8格式的字符,两者编码不匹配导致输出时触发编码错误,代码本身没有问题。

临时解决方法(单次生效)

在Git Bash中先运行以下命令,再执行Python脚本:

export PYTHONIOENCODING=utf-8

永久解决方法(全局生效)

编辑Git Bash的配置文件~/.bashrc或~/.bash_profile,添加以下内容:

export PYTHONIOENCODING=utf-8

保存文件后重启Git Bash,后续运行Python脚本都会自动使用UTF-8编码输出。

代码适配方案(不推荐)

如果不想修改终端配置,可以在脚本开头添加以下代码,强制Python输出使用UTF-8编码:

import sys
sys.stdout.reconfigure(encoding='utf-8')

这种方法仅对当前脚本生效,会降低代码在不同环境下的通用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:15:47