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

CentOS服务器Python3.6 UnicodeEncodeError问题求助

解决CentOS下Python3.6脚本输出Unicode字符的UnicodeEncodeError问题

问题根源

CentOS环境中,Python3.6的标准输出(stdout)可能被系统环境强制设置为ASCII编码,即便尝试手动编码转换或设置PYTHONIOENCODING环境变量,也可能因执行上下文(比如CGI、特定服务调用)导致环境变量未生效,最终输出Unicode字符时触发编码错误。

程序内解决方案

直接在脚本中重设标准输出的编码,使用codecs模块将stdout包装为UTF-8编码的流,确保所有输出都以UTF-8编码发送。

修改后的测试代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys, os, traceback, time
import codecs

# 核心修复:用UTF-8重新包装标准输出
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())

sys.path.append(os.path.expanduser("~") + "/EF5/LIB")

import EF # 测试无关,移除后问题依旧

print("Content-Type: text/plain;charset=utf-8\n")

def tester(n):
    b = n.encode('utf-8')
    s = b.decode('utf-8')
    return s + "!"

try:
    print("Hello 高欧凡")
except Exception as err:
    print(type(err))
    print(err)
    print(traceback.format_exc())

补充说明

  • sys.stdout.detach()会分离原stdout的缓冲区,避免编码冲突;codecs.getwriter('utf-8')则创建一个UTF-8编码的写入器,重新赋值给sys.stdout后,所有print操作都会自动以UTF-8编码输出。
  • 若需同时处理标准错误(stderr),可按同样方式重设:
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach())
    
  • 该方法无需修改服务器配置,完全在脚本内完成编码控制,适用于CGI、命令行等各种执行场景。

内容的提问来源于stack exchange,提问作者Xerix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:52:40