使用Python脚本在Ubuntu的终端中显示UTF8引号 [英] Displaying UTF8 stings in Ubuntu's terminal with a Python script
问题描述
在我的Python脚本在Ubuntu的命令行运行,它从MySQL数据库选择UTF8编码的内容。
In my Python script running at the command line on Ubuntu, it's selecting UTF8-encoded content from a MySQL database.
然后,我打印字符串
显示的字符串有编码问题,因为它们没有正确显示重音字符。如何解决此问题?
The displayed strings have an encoding problem, as they don't show the accented characters correctly. How do I fix this?
最好是,脚本将决定而不是设置系统环境,以确保在其他系统上轻松运行。
Preferably, the script would make the decision, rather than setting a system environment, to ensure easy running on other systems.
推荐答案
强烈建议您不要使用?作为替代字符。只需将输出编码设置为UTF-8,然后使用它。
It is very strongly recommended that you not use "?" as a replacement char. Just set your output encoding to UTF-8 and be done with it.
for s in ("stdin","stdout","stderr"):
setattr(sys, s, io.TextIOWrapper(getattr(sys, s).detach(), encoding="utf8"))
或者,将 PYTHONIOENCODING
envariable设置为utf8,以使python停止猜测输出编码。
Alternately, set your PYTHONIOENCODING
envariable to utf8 so that python stops guessing about the output encoding.
这两种方法都比手动编码好得多,这是愚蠢的。
Either approach is infinitely much better than manually encoding, which is stupid.
如果您拒绝升级Python3,我还推荐
If you refuse to upgrade to Python3, I also recommend
from __future__ import unicode_literals
可清除所有那些愚蠢的 u'...'
内容。
to banish all that stupid u'...'
stuff.
最近我开始所有的Python程序,像这样:
Lately I’ve starting all my Python progams like this:
#!/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脚本在Ubuntu的终端中显示UTF8引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!