PyInstaller打包含中文字符脚本报ascii编码错误,是否为其自身问题?
问题:PyInstaller打包含中文的Python脚本后执行报错?
test.py仅包含以下代码:
s = '你好' print(s)
直接运行脚本正常输出:
python3 test.py 你好
使用PyInstaller打包:
python3 -m PyInstaller --onefile test.py
执行打包后的程序时出现报错:
./test Traceback (most recent call last): File "test.py", line 3, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) [7228] Failed to execute script 'test' due to unhandled exception!
请问这是否是PyInstaller的问题?
分析与解决
这不是PyInstaller的问题,核心原因是打包后的可执行文件运行时,标准输出的编码被默认设置为ASCII;而直接运行Python脚本时,终端会自动适配UTF-8编码,因此不会触发编码错误。
可以通过以下几种方式解决:
- 在代码中显式指定标准输出编码:修改test.py,强制将标准输出设置为UTF-8编码
import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') s = '你好' print(s) - 运行前设置环境变量:执行打包后的程序前,先指定Python的IO编码为UTF-8
export PYTHONIOENCODING=utf-8 ./test - 打包时指定环境变量:修改PyInstaller生成的.spec文件,在EXE部分添加编码环境变量配置后重新打包
# 其他代码保持不变 exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='test', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True, env={'PYTHONIOENCODING': 'utf-8'}) # 添加此行
内容的提问来源于stack exchange,提问作者Liang-Liang Han
相关产品推荐
相关产品推荐

