Skip to content

Instantly share code, notes, and snippets.

@elvisw
Last active May 10, 2026 01:38
Show Gist options
  • Select an option

  • Save elvisw/287d64b018dab3905502e94893ab2b80 to your computer and use it in GitHub Desktop.

Select an option

Save elvisw/287d64b018dab3905502e94893ab2b80 to your computer and use it in GitHub Desktop.
Git Bash UTF-8 编码问题完整解决方案
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UTF-8 编码控制台输出测试脚本
测试内容:中文、emoji表情、字符模拟进度条
"""
import sys
import time
import io
def test_utf8_output():
"""测试UTF-8编码输出"""
print("=" * 60)
print("UTF-8 编码控制台输出测试")
print("=" * 60)
print()
# 1. 测试中文输出
print("【测试1】中文字符输出:")
print(" - 简体中文:你好,世界!")
print(" - 繁体中文:你好,世界!")
print(" - 特殊字符:①②③④⑤ © ® ™")
print()
# 2. 测试emoji表情
print("【测试2】Emoji表情输出:")
print(" - 表情符号:😀 😃 😄 😁 😆")
print(" - 手势符号:👍 👎 👏 🙏 💪")
print(" - 物品符号:🎉 🎊 🎁 🎈 🎀")
print(" - 自然符号:🌸 🌺 🌻 🌹 🌷")
print(" - 食物符号:🍎 🍊 🍋 🍇 🍉")
print(" - 动物符号:🐶 🐱 🐭 🐹 🐰")
print()
# 3. 测试字符模拟进度条
print("【测试3】字符模拟进度条:")
print()
# 进度条样式1:方块进度条
print(" 样式1 - 方块进度条:")
for i in range(0, 101, 5):
filled = "█" * (i // 5)
empty = "░" * (20 - i // 5)
progress = f"\r 进度:[{filled}{empty}] {i:3d}%"
print(progress, end="", flush=True)
time.sleep(0.1)
print()
# 进度条样式2:箭头进度条
print("\n 样式2 - 箭头进度条:")
for i in range(0, 101, 5):
filled = "━" * (i // 5)
empty = "─" * (20 - i // 5)
arrow = "▶" if i < 100 else "✓"
progress = f"\r 进度:[{filled}{empty}]{arrow} {i:3d}%"
print(progress, end="", flush=True)
time.sleep(0.1)
print()
# 进度条样式3:彩色进度条(使用ANSI转义码)
print("\n 样式3 - 彩色进度条:")
for i in range(0, 101, 5):
filled = "█" * (i // 5)
empty = "░" * (20 - i // 5)
# ANSI颜色代码:绿色填充,灰色空白
colored_filled = f"\033[32m{filled}\033[0m"
colored_empty = f"\033[90m{empty}\033[0m"
progress = f"\r 进度:[{colored_filled}{colored_empty}] {i:3d}%"
print(progress, end="", flush=True)
time.sleep(0.1)
print()
# 4. 测试混合内容
print("\n【测试4】混合内容输出:")
print(" 状态:✅ 成功 | ⏳ 处理中 | ❌ 失败")
print(" 进度:▓▓▓▓▓▓▓▓░░░░ 60% 完成")
print(" 评分:★★★★☆ (4.5/5.0)")
print(" 方向:← ↑ → ↓ ↖ ↗ ↘ ↙")
print()
# 5. 输出系统编码信息
print("【系统信息】")
print(f" Python版本:{sys.version}")
print(f" 默认编码:{sys.getdefaultencoding()}")
print(f" 标准输出编码:{sys.stdout.encoding}")
print(f" 文件系统编码:{sys.getfilesystemencoding()}")
print()
print("=" * 60)
print("✅ 测试完成!")
print("=" * 60)
if __name__ == "__main__":
try:
test_utf8_output()
except Exception as e:
print(f"\n❌ 测试出错:{e}")
import traceback
traceback.print_exc()

Git Bash UTF-8 编码问题完整解决方案

问题描述

在 Windows 上使用 Git Bash 执行 Python 脚本时,由于:

  1. Git Bash 使用非交互式 shell,不加载 ~/.bashrc
  2. Windows PowerShell 5 默认使用 GBK 编码(代码页 936)
  3. Python 子进程无法继承环境变量

导致中文、emoji 等 UTF-8 字符输出乱码或报错。

解决方案

方案1:Python 别名(推荐)⭐⭐⭐

~/.bashrc 中添加别名,强制设置环境变量:

# Python UTF-8 别名
alias python='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python'
alias python3='PYTHONIOENCODING=utf-8 PYTHONUTF8=1 python3'

优点:

  • 简单直接,无需额外文件
  • 确保环境变量传递给 Python 进程
  • 对所有 shell 类型有效

方案2:包装脚本

创建 ~/.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

方案3:登录 Shell

使用登录 shell 执行命令(会加载 ~/.bash_profile):

bash -l -c 'python script.py'

配置文件说明

~/.bashrc

# 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 "$@"; }

~/.bash_profile

# generated by Git for Windows
test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc

# 设置非交互式 shell 环境变量
export BASH_ENV="$HOME/.bash_env"

~/.bash_env

# 非交互式 bash 环境变量设置
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1

验证测试

运行测试脚本验证配置:

python test_utf8.py

应该看到:

  • ✅ 中文字符正常显示
  • ✅ Emoji 表情正常显示
  • ✅ 进度条字符正常显示
  • ✅ 无 UnicodeEncodeError 错误

注意事项

  1. 环境变量作用域

    • Windows 用户级环境变量:影响所有进程
    • .bashrc 中的 export:仅影响交互式 shell
    • 别名:确保环境变量传递给子进程
  2. Shell 类型

    • 交互式 shell:加载 ~/.bashrc~/.bash_profile
    • 非交互式 shell:仅加载 $BASH_ENV 指定的文件
    • 登录 shell:加载 ~/.bash_profile
  3. 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)"

检查 Shell 类型

echo "Shell: $0"
shopt -q login_shell && echo "登录 shell" || echo "非登录 shell"

重新加载配置

source ~/.bashrc
source ~/.bash_profile

参考资料

#!/bin/bash
# UTF-8 配置验证脚本
# 加载配置文件
# source "$HOME/.bashrc" 2>/dev/null
echo "============================================================"
echo "Git Bash UTF-8 配置验证"
echo "============================================================"
echo
# 1. 检查环境变量
echo "【1】环境变量检查:"
echo " PYTHONIOENCODING: ${PYTHONIOENCODING:-未设置}"
echo " PYTHONUTF8: ${PYTHONUTF8:-未设置}"
echo " BASH_ENV: ${BASH_ENV:-未设置}"
echo
# 2. 检查 Shell 类型
echo "【2】Shell 类型:"
echo " 当前 Shell: $0"
if shopt -q login_shell 2>/dev/null; then
echo " 登录 Shell: 是"
else
echo " 登录 Shell: 否"
fi
echo
# 3. 检查 Python 编码
echo "【3】Python 编码设置:"
python -c "import sys, os; print(f' stdout encoding: {sys.stdout.encoding}'); print(f' PYTHONIOENCODING env: {os.environ.get(\"PYTHONIOENCODING\", \"未设置\")}')"
echo
# 4. 测试中文输出
echo "【4】中文输出测试:"
echo " 简体中文:你好,世界!"
echo " 繁体中文:你好,世界!"
echo " 特殊字符:①②③④⑤ © ® ™"
echo
# 5. 测试 Python 中文输出
echo "【5】Python 中文输出测试:"
python -c "print(' Python 中文:你好,世界!'); print(' Python emoji:😀 👍 ✅')"
echo
# 6. 检查配置文件
echo "【6】配置文件状态:"
for file in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.bash_env"; do
if [[ -f "$file" ]]; then
echo "$file 存在"
else
echo "$file 不存在"
fi
done
echo
# 7. 检查别名
echo "【7】Python 别名检查:"
if alias python &>/dev/null; then
echo " ✅ python 别名已设置"
alias python | sed 's/^/ /'
else
echo " ⚠️ python 别名未设置"
fi
echo
echo "============================================================"
echo "✅ 验证完成!"
echo "============================================================"
@elvisw

elvisw commented May 10, 2026

Copy link
Copy Markdown
Author

claude code直接执行python -c "脚本"的时候,还会出错。这是因为这种情况下Git Bash 使用非交互式 shell,不加载 ~/.bashrc.bash_profile。所以需要设置环境变量BASH_ENV$HOME/.bashrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment