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

PyCharm中pytest调用tqdm触发UnicodeEncodeError内部错误

解决PyCharm中pytest调用tqdm触发UnicodeEncodeError的问题

核心问题分析

PyCharm内置控制台编码与系统终端编码不一致,导致tqdm输出Unicode字符时触发编码转换失败;错误栈显示的PyCharm版本与实际不符,大概率是旧版本缓存或插件残留引发的显示异常。

具体解决步骤

1. 统一PyCharm控制台编码

  • 打开File > Settings > Editor > General > Console(Windows/Linux)或PyCharm > Settings > Editor > General > Console(Mac)
  • 将Console encoding和Default encoding for properties files均设置为UTF-8
  • 重启PyCharm使设置生效

2. 强制tqdm使用UTF-8编码输出

在测试代码或main.py中添加以下代码,强制tqdm以UTF-8编码输出:

from tqdm import tqdm
import sys

# 方法1:重写tqdm的write方法
tqdm.write = lambda x: print(x, file=sys.stdout, encoding='utf-8')

# 方法2:初始化tqdm时指定编码
# tqdm_obj = tqdm(your_iterable, encoding='utf-8')

3. 清理PyCharm缓存并重置插件

  • 打开File > Invalidate Caches...,勾选Clear file system cache and local history后点击Invalidate and Restart
  • 检查项目Python解释器的依赖版本:File > Settings > Project: [你的项目名] > Python Interpreter,确保tqdm、pytest版本与系统终端中使用的一致
  • 卸载可能存在的旧版本pytest/tqdm相关插件,重新安装适配PyCharm 2022.3.1的版本

4. 切换PyCharm运行终端为系统终端

  • 打开Run > Edit Configurations...,选择对应的pytest配置
  • 在Execution标签下勾选Emulate terminal in output console
  • 保存配置后重新运行pytest测试

验证标准

修改配置后重新运行测试,若UnicodeEncodeError消失,且错误栈中显示的PyCharm版本与实际2022.3.1一致,则问题解决。

内容的提问来源于stack exchange,提问作者FluidMechanics Potential Flows

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:15:27