简体   繁体   English

Python 打印 unicode 字符而不是 ASCII

[英]Python printing unicode characters instead of ASCII

I want to print an ASCII text but when I run the script, it throws me an error:我想打印一个 ASCII 文本,但是当我运行脚本时,它抛出一个错误:

$ python test.py Traceback (most recent call last): 
   File "C:\Users\wooxh\Desktop\Materialy\XRichPresence\test.py", 
       line 1, in <module> print(""" File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\encodings\cp1250.py", 
           line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 
   'charmap' codec can't encode characters in position 2-4: character maps to <undefined>

Here's the code这是代码

print("""
██╗  ██╗██████╗ ██████╗  ██████╗
╚██╗██╔╝██╔══██╗██╔══██╗██╔════╝
 ╚███╔╝ ██████╔╝██████╔╝██║     
 ██╔██╗ ██╔══██╗██╔═══╝ ██║     
██╔╝ ██╗██║  ██║██║     ╚██████╗
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝      ╚═════╝
""")

Looks like Python is identifying your code page as 1250, which doesn't include the characters you're using.看起来 Python 将您的代码页标识为 1250,其中不包括您正在使用的字符。 If chcp reports you're actually using code page 437 (common in cmd.exe ) you can do:如果chcp报告您实际上使用的是代码页 437(常见于cmd.exe ),您可以执行以下操作:

import sys

sys.stdout.buffer.write("""
██╗  ██╗██████╗ ██████╗  ██████╗
╚██╗██╔╝██╔══██╗██╔══██╗██╔════╝
 ╚███╔╝ ██████╔╝██████╔╝██║     
 ██╔██╗ ██╔══██╗██╔═══╝ ██║     
██╔╝ ██╗██║  ██║██║     ╚██████╗
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝      ╚═════╝
""".encode('cp437'))

to explicitly encode to the correct code page and write it.显式编码到正确的代码页并编写它。 Otherwise, I'd suggest enabling Python's forced UTF-8 runtime mode , which should allow your original code (with no call to encode ) to work (possibly dropping or replacing characters not representable by the terminal).否则,我建议启用 Python 的强制 UTF-8 运行时模式,这应该允许您的原始代码(不调用encode )工作(可能删除或替换终端无法表示的字符)。 All you'd change is your run command:您只需更改运行命令:

> python -X utf8 test.py

or explicitly define PYTHONUTF=1 in your environment to turn it on without a command line switch.或者在您的环境中明确定义PYTHONUTF=1以在没有命令行开关的情况下将其打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM