在 Ubuntu 上的命令行中运行的 Python 脚本中,它从 MySQL 数据库中选择 UTF8 编码的内容。
然后,我想将字符串打印到控制台。
显示的字符串存在编码问题,因为它们无法正确显示重音字符。我该如何解决这个问题?
最好由脚本做出决定,而不是设置系统环境,以确保在其他系统上轻松运行。
最佳答案
强烈建议您不要使用“?”作为替换字符。只需将输出编码设置为 UTF-8 即可完成。
for s in ("stdin","stdout","stderr"):
setattr(sys, s, io.TextIOWrapper(getattr(sys, s).detach(), encoding="utf8"))
或者,将 PYTHONIOENCODING
envariable 设置为 utf8,以便 python 停止猜测输出编码。
这两种方法都比手动编码好得多,手动编码是愚蠢的。
如果你拒绝升级到Python3,我也推荐
from __future__ import unicode_literals
消除所有愚蠢的u'...'
东西。
最近我所有的 Python 程序都是这样启动的:
#!/usr/bin/env python3.2
# -*- coding: UTF-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import re
import sys
import os
if not (("PYTHONIOENCODING" in os.environ)
and
re.search("^utf-?8$", os.environ["PYTHONIOENCODING"], re.I)):
sys.stderr.write(sys.argv[0] + ": Please set your PYTHONIOENCODING envariable to utf8\n")
sys.exit(1)
import unicodedata
if unicodedata.unidata_version < "6.0.0":
print("WARNING: Your old UCD is out of date, expected at least 6.0.0 but got",
unicodedata.unidata_version)
wide_enough = (sys.maxunicode >= 0x10FFFF)
if not wide_enough:
print("WARNING: Narrow build detected, your Python lacks full Unicode support!!")
关于python - 使用 Python 脚本在 Ubuntu 终端中显示 UTF 8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030857/