在 Windows 上使用 Git Bash 执行 Python 脚本时,由于:
- Git Bash 使用非交互式 shell,不加载
~/.bashrc - Windows PowerShell 5 默认使用 GBK 编码(代码页 936)
- Python 子进程无法继承环境变量
导致中文、emoji 等 UTF-8 字符输出乱码或报错。
在 ~/.bashrc 中添加别名,强制设置环境变量:
# Python UTF-8 别名
alias python='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python'
alias python3='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python3'优点:
- 简单直接,无需额外文件
- 确保环境变量传递给 Python 进程
- 对所有 shell 类型有效
创建 ~/.local/bin/python-utf8 脚本:
#!/bin/bash
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1
exec python "$@"添加到 PATH:
export PATH="$HOME/.local/bin:$PATH"使用:python-utf8 script.py
使用登录 shell 执行命令(会加载 ~/.bash_profile):
bash -l -c 'python script.py'# Python UTF-8 编码设置
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1
export BASH_ENV="$HOME/.bash_env"
# Python 别名
alias python='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python'
alias python3='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python3'
# PowerShell UTF-8 包装器
_ps_utf8_wrapper() {
local exe="$1"; shift
local pre_args=()
local cmd=""
local found_command=false
while [[ $# -gt 0 ]]; do
case "$1" in
-Command|-c)
found_command=true
shift
cmd="$*"
break
;;
*)
pre_args+=("$1")
shift
;;
esac
done
if $found_command && [[ -n "$cmd" ]]; then
command "$exe" "${pre_args[@]}" -Command \
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $cmd"
else
command "$exe" "${pre_args[@]}"
fi
}
powershell() { _ps_utf8_wrapper powershell.exe "$@"; }
pwsh() { _ps_utf8_wrapper pwsh.exe "$@"; }# generated by Git for Windows
test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc
# 设置非交互式 shell 环境变量
export BASH_ENV="$HOME/.bash_env"# 非交互式 bash 环境变量设置
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1运行测试脚本验证配置:
python test_utf8.py应该看到:
- ✅ 中文字符正常显示
- ✅ Emoji 表情正常显示
- ✅ 进度条字符正常显示
- ✅ 无
UnicodeEncodeError错误
-
环境变量作用域:
- Windows 用户级环境变量:影响所有进程
.bashrc中的 export:仅影响交互式 shell- 别名:确保环境变量传递给子进程
-
Shell 类型:
- 交互式 shell:加载
~/.bashrc和~/.bash_profile - 非交互式 shell:仅加载
$BASH_ENV指定的文件 - 登录 shell:加载
~/.bash_profile
- 交互式 shell:加载
-
PowerShell 编码:
- PowerShell 5:默认 GBK(代码页 936)
- PowerShell 7:默认 UTF-8
- 包装器函数确保 UTF-8 输出
echo "PYTHONIOENCODING: $PYTHONIOENCODING"
echo "PYTHONUTF8: $PYTHONUTF8"
python -c "import sys; print('stdout encoding:', sys.stdout.encoding)"echo "Shell: $0"
shopt -q login_shell && echo "登录 shell" || echo "非登录 shell"source ~/.bashrc
source ~/.bash_profile
claude code直接执行python -c "脚本"的时候,还会出错。这是因为这种情况下Git Bash 使用非交互式 shell,不加载
~/.bashrc和.bash_profile。所以需要设置环境变量BASH_ENV为$HOME/.bashrc。