jackwener / jackwener/xiaohongshu-cli

xhs login --qrcode 在 Windows GBK 终端崩溃(UnicodeEncodeError: emoji 无法编码)

Open Beginner friendly
#43 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
2.6k
Forks
272
PR merge metrics
No merged PRs in 30d

Description

## 环境信息

| 项目 | 值 |
|------|-----|
| OS | Windows 11 Home China 10.0.26200 |
| Python | 3.12.3 |
| xiaohongshu-cli | v0.6.4(通过 `uv tool install xiaohongshu-cli` 安装) |
| 终端编码 | GBK(Windows 简体中文默认) |

## 现象

执行 `xhs login --qrcode` 时程序直接崩溃:

```
File "...\xhs_cli\qr_login.py", line 65, in _emit_status
print(msg)
UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f511' in position 0: illegal multibyte sequence
```

二维码尚未显示,程序就已退出。

## 根因

`qr_login.py:65` 中 `_emit_status` 函数使用 `print()` 输出包含 emoji 字符(🔑 `\U0001f511`)的状态消息。

Windows 中文版终端默认编码为 GBK,`print()` 使用 `sys.stdout.encoding`(即 GBK)编码输出。GBK 不支持 emoji 字符,`print()` 默认使用 `errors='strict'`,导致直接抛出 `UnicodeEncodeError`。

## 复现步骤

```bash
# 在 Windows 中文终端(cmd / PowerShell / Windows Terminal)中:
xhs login --qrcode
# → UnicodeEncodeError 崩溃
```

## 绕过方案

设置环境变量强制 UTF-8 输出:

```bash
PYTHONIOENCODING=utf-8 xhs login --qrcode
```

之后二维码正常显示,扫码登录成功:

```
🔑 Starting browser-assisted QR login...
📱 Scan the QR code below with the Xiaohongshu app:
[二维码正常显示]
⏳ Waiting for QR code scan...
📲 Scanned! Waiting for confirmation...
✅ Login confirmed!
```

## 建议修复方案

在 CLI 入口或输出函数中处理编码兼容性,避免因终端编码限制导致程序崩溃。例如:

**方案 A:在 CLI 入口统一设置**

```python
import sys
if sys.stdout.encoding and sys.stdout.encoding.lower() not in ('utf-8', 'utf8'):
sys.stdout.reconfigure(errors='replace')
sys.stderr.reconfigure(errors='replace')
```

**方案 B:在 `_emit_status` 中容错**

```python
def _emit_status(on_status, msg):
try:
print(msg)
except UnicodeEncodeError:
print(msg.encode(sys.stdout.encoding, errors='replace').decode(sys.stdout.encoding))
```

**方案 C:移除或替换 emoji**

将 emoji 替换为 ASCII 符号(如 `🔑` → `[key]`,`📱` → `[scan]`),保证在所有终端环境下兼容。

## 影响范围

所有使用非 UTF-8 终端的 Windows 用户,主要是简体中文(GBK)、繁体中文(Big5)、日文(Shift-JIS)等 CJK 环境。这也是 `--qrcode` 功能在 Windows 上的主要使用路径(因为 Chrome 127+ 的 Cookie 提取已失效,见 #42)。

Contributor guide

No contributing guide indexed for this repository

Research direction

Start in xhs_cli/qr_login.py at _emit_status around line 65 and review how status messages are printed. Reproduce xhs login --qrcode in a Windows GBK terminal, then verify the command no longer crashes before displaying the QR code and that the login flow still completes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cli
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.