Skip to main content
 首页 » 编程设计

python之检查 stdout 是否支持 unicode

2025年05月04日7mfrbuaa

如果我想打印 Unicode,我通常会这样做:

print("There are ", end="") 
try: 
    print(u"\u221E", end="")  # ∞ 
    unicode_support = True 
except UnicodeError: 
    print("infinity", end="") 
    unicode_support = False 
print(" ways to get Unicode wrong.") 
 
if unicode_support: 
    print(u"\U0001F440 see you have a Unicode font.") 
else: 
    print("You do not have Unicode support.") 

如果我想从方法或类似的东西返回 Unicode 字符串,这将不起作用,因为 Python 将始终理解其中包含 Unicode 的字符串文字,并且仅在打印到不支持 Unicode 的内容时抛出此错误。我想做这样的事情:

import sys as _sys 
 
UNICODE_SUPPORT = _sys.stdout.unicode_support 
 
def get_heart(): 
    if UNICODE_SUPPORT: 
        return u"\u2665"  # ♥ 
    return "heart" 
 
print("I{}U".format(get_heart.upper())) 

如果当前标准输出支持 Unicode,我希望 sys.stdout.supports_unicode 的等价物为 True,否则为 False。

请您参考如下方法:

这主要是一个 hack,但类似的东西,也许:

 UNICODE_SUPPORT = sys.stdout.encoding in ('UTF-8', 'UTF-16', 'UTF-16LE', 'UTF-16BE', 'UTF-32', 'UTF-32LE', 'UTF32BE') 

或者(归功于 Martijn Pieters):

 UNICODE_SUPPORT = sys.stdout.encoding.lower().startswith('utf') 

简单地说,Unicode 是一个巨大的列表,包含全世界用于书写语言的所有字符。包括古代语言和许多常见和不常见的符号 ( U+1F4A9 )。该列表中的每个项目都称为一个代码点,并由一个数字标识。

UTF-8、UTF-16 和 UTF-32 是编码专门设计的,能够将所有代码点编码为字节序列。 UTF-16和UTF-32是固定大小的多字节编码,既有大端也有小端。

Unicode 被设计为通用,根据定义,UTF-... 以外的任何编码仅支持 Unicode 的一个子集。 cp1252 和 iso-8859-15 这样的编码,(部分)支持 Unicode 的拉丁子集。